3

我不精通网络技术,想知道是否有办法 - 一个想法是使用setWebhook - 让电报机器人做简单的事情(比如只要有人发送它就一遍又一遍地重复相同的消息一条消息)而不设置服务器

我认为可能没有办法解决它,因为我需要解析 JSON 对象以获取 chat_id 以便能够发送消息......但我希望这里有人可能知道方法。

例如

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 对其进行了测试,并且它可以工作......但当然,它总是只会向同一个聊天发送消息,无论它在哪里收到消息。

4

2 回答 2

7

这是一个非常简单的 Python 机器人示例,您可以在您的 PC 上运行它而无需服务器。

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)

资源

我正在研究的机器人

于 2015-06-29T18:02:57.157 回答
1

这真的很有趣,但您肯定需要一个服务器来解析 JSON 值并从中获取 chat_id。

于 2015-06-26T15:36:30.857 回答