Send messages to telegram group without user input

Joe picture Joe · Mar 10, 2018 · Viewed 15.6k times · Source

I'm trying to build a bot which automatically sends a message whenever there is an update in the latest news using python. Following is what I did.

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

How can I update my code so that the bot publishes the latest news to all the groups to which it is added? I got the chat_id using: bot.get_updates()[-1].message.chat.id Any suggestions on how to automate this?

Answer

576i picture 576i · Apr 14, 2018

Using the python-telegram-bot api, you can send a message like this

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

you need the "bot" and "id"

I keep these in a dictionary called "mybots" which I fill/update when people interact with the bot for the first time / or on later communication with the bot. It's possible to pickle this dictionary to keep it persistant.

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!')