设置没有服务器的Telegram机器人

Doi*_*ois 3 json webhooks telegram-bot

我不太熟悉网络技术,想知道是否有一种方法-一种想法是使用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>
Run Code Online (Sandbox Code Playgroud)

我已经使用硬编码的聊天ID对其进行了测试,并且可以正常工作……但是,无论它在何处接收消息,它当然始终只会向该聊天发送消息。

Mar*_*ama 5

这是一个非常简单的Python bot示例,您无需服务器即可在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)
Run Code Online (Sandbox Code Playgroud)

资源

我正在努力


Ema*_*emi 0

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