设置没有服务器的Telegram机器人 [英] Setting up a Telegram bot without a server
问题描述
我不太熟悉网络技术,想知道是否有办法-一个想法是使用 setWebhook -使电报机器人做简单的事情(例如只需在有人发送邮件时一遍又一遍地重复同一封邮件).无需设置服务器.
I'm not well versed with web techniques and would like to know if there's a way - an idea would be to use setWebhook - to make a telegram bot do simple stuff (like simply repeat the same message over and over again whenever someone sends it a message) without setting up a server.
我认为可能无法解决,因为我需要解析JSON对象以获取chat_id才能发送消息...但是我希望这里的人可能知道一种方法.
I think there might be no way around it because I need to parse the JSON object to get the chat_id to be able to send messages... but I'm hoping someone here might know a way.
例如
https://api.telegram.org/bot<token>/setWebHook?url=https://api.telegram.org/bot<token>/sendMessage?text=Hello%26chat_id=<somehow get the chat_id>
我已经使用硬编码的聊天ID对其进行了测试,它可以工作...但是,当然,无论它在哪里接收消息,它始终只会向该聊天发送消息.
I've tested it with a hard-coded chat id and it works... but of course it'll always only send messages to that same chat, regardless of where it received the message.
推荐答案
这是一个非常简单的Python机器人示例,您无需服务器即可在PC上运行它.
Here is a very simple Python bot example, you can run this on your PC no need for a server.
import requests
import json
from time import sleep
# This will mark the last update we've checked
last_update = 0
# Here, insert the token BotFather gave you for your bot.
token = 'YOUR_TOKEN_HERE'
# This is the url for communicating with your bot
url = 'https://api.telegram.org/bot%s/' % token
# We want to keep checking for updates. So this must be a never ending loop
while True:
# My chat is up and running, I need to maintain it! Get me all chat updates
get_updates = json.loads(requests.get(url + 'getUpdates').content)
# Ok, I've got 'em. Let's iterate through each one
for update in get_updates['result']:
# First make sure I haven't read this update yet
if last_update < update['update_id']:
last_update = update['update_id']
# I've got a new update. Let's see what it is.
if 'message' in update:
# It's a message! Let's send it back :D
requests.get(url + 'sendMessage', params=dict(chat_id=update['message']['chat']['id'], text=update['message']['text']))
# Let's wait a few seconds for new updates
sleep(3)
这篇关于设置没有服务器的Telegram机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!