【问题标题】:Send messages to telegram group without user input无需用户输入即可向电报组发送消息
【发布时间】:2018-08-19 06:31:10
【问题描述】:

我正在尝试构建一个机器人,它会在使用 python 的最新消息有更新时自动发送消息。以下是我所做的。

companies = {
    "name_1": {
        "rss": "name_1 rss link",
        "link": "name_1 link"
    }
}

import feedparser as fp
import time, telebot
token = <TOKEN>
bot = telebot.TeleBot(token)
LIMIT = 1
while True:
    def get_news():
        count = 1
        news = []
        for company, value in companies.items():
            count = 1
            if 'rss' in value:
                d = fp.parse(value['rss'])
                for entry in d.entries:
                    if hasattr(entry, 'published'):
                        if count > LIMIT:
                            break
                        news.append(entry.link)
                        count = count + 1

        return (news)
    val = get_news()
    time.sleep(10)
    val2 = get_news()
    try:
        if val[0]!=val2[0]:
            bot.send_message(chat_id= "Hardcoded chat_id", text=val2[0])
    except Exception:
        pass

如何更新我的代码,以便机器人将最新消息发布到它添加到的所有组? 我得到了 chat_id 使用: bot.get_updates()[-1].message.chat.id 关于如何实现自动化的任何建议?

【问题讨论】:

标签: python-3.x telegram telegram-bot python-telegram-bot


【解决方案1】:

使用 python-telegram-bot api,您可以发送这样的消息

bot.send_message(id, text='Message')

你需要“bot”和“id”

我将这些保存在名为“mybots”的字典中,当人们第一次与机器人交互/或稍后与机器人通信时,我会填写/更新该字典。可以腌制这本字典以保持它​​的持久性。

mybots = {}

def start(bot, update):
    """Send a message when the command /start is issued."""
      mybots[update.message.chat_id] = bot
      update.message.reply_text('Hello{}!'.format(
           update.effective_chat.first_name))

def send_later():
    for id, bot in mybots.items():
        bot.send_message(id, text='Beep!')

【讨论】:

    【解决方案2】:

    简而言之,您可以使用sendMessage() 向特定组或用户发送消息。

    bot.sendMessage(chat_id=chat_id, text=msg)
    

    完整的代码,

    import telegram
    
    
    #token that can be generated talking with @BotFather on telegram
    my_token = ''
    
    def send(msg, chat_id, token=my_token):
        """
        Send a message to a telegram user or group specified on chatId
        chat_id must be a number!
        """
        bot = telegram.Bot(token=token)
        bot.sendMessage(chat_id=chat_id, text=msg)
    

    【讨论】:

    • 在我的情况下,该组是“prueba”。我必须在代码中的哪里包含组名?此代码将味精发送给机器人(但没人能看到,只有我),但不能发送给名为“prueba”的组
    • 嗨@kamome,您不必在代码中添加您的组名,而是必须在代码中添加chat_id。如果您在查找特定群组的 chat_id id 时遇到问题,请refer this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多