【问题标题】:Setting up a Telegram bot without a server在没有服务器的情况下设置 Telegram 机器人
【发布时间】:2015-09-13 10:53:34
【问题描述】:

我不精通网络技术,想知道是否有办法 - 一个想法是使用 setWebhook - 让 telegram bot 做一些简单的事情(比如简单地重复相同的消息并每当有人向它发送消息时重试)无需设置服务器

我认为可能没有办法解决它,因为我需要解析 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 对其进行了测试,它可以正常工作...但当然,它总是只会向同一个聊天发送消息,无论它在哪里收到消息。

【问题讨论】:

  • 你看过 OpenShift 吗?三个小“齿轮”是免费的,便于使用服务器进行实验。
  • 哦...感谢您的介绍,我决定在 Google App Engine 上设置一个服务器,现在它工作得很好。我知道这很愚蠢,但这是我运行的两个机器人。 telegram.me/serhanbottelegram.me/gregorybot

标签: json webhooks telegram-bot


【解决方案1】:

这是一个非常简单的 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)

Source

Bot I'm working on

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 有没有没有SSL认证的rubbot 选项?
    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多