Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send messages to telegram group without user input

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?

like image 808
Joe Avatar asked Mar 10 '18 22:03

Joe


2 Answers

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!')
like image 158
576i Avatar answered Dec 07 '22 21:12

576i


In short, you can use sendMessage() to send message to a specific group or user.

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

the complete code,

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)
like image 31
Sumithran Avatar answered Dec 07 '22 20:12

Sumithran