skip to Main Content

I am wondering how I could store/read out a user chat ID to later send them messages.

Example would be, that the user is adding my telegram bot and sends him a message.
Later on in my program at some point, when a sepcific situation occurs, I want to send a message to the specific user.

For a simple example I have this code:

a=1
b=2

if a > b:
     # at this point python should send a message to a user via telegram privat chat

else:
    # send a different message

I know how to handle a response to a command sent by the user in the telegram chat, but not how to send a message to a user without receiving a command first. I think there fore I would need to have a way to store the users chat Id first to later refer to that Id when sending the message.

The point is I want to compile my program to .exe later on and send it to some friends and it should work for them as well.

2

Answers


  1. You can simply add the id in a list WHITOUT ANY THIRD PARTS PAKAGE

    import telebot
    
    TOKEN = ""
    bot = telebot.TeleBot(TOKEN)
    
    admin = # your chat id
    users = []
    
    @bot.message_handler(commands=['start'])
    def start_message(msg):
        bot.send_message(msg.chat.id, 'Welcome!')
        if msg.chat.id not in users: # if the id isn't already in the users list
            users.append(msg.chat.id)
    
    @bot.message_handler(commands=['send_at_all']) # A way to use the list
    def sendAtAll(msg):
        if msg.chat.id == admin: # only if YOU start the command the message will be sent
            for id in users: # for every user that has start the bot
                bot.send_message(id, "I'm sending this message at all the users")
    
    # If an user wants to stop the notifications...
    
    @bot.message_handler(commands=['unsubscribe'])
    def sendAtAll(msg):
        del users[msg.chat.id]
        bot.send_message(msg.chat.id, "If you want to receive the notification click /start")
    
    
    # Every time you are going to restart the bot polling the content of the users list will be deleated so...
    
    @bot.message_handler(commands=['save_user_list'])
    def sendAtAll(msg):
        if msg.chat.id == admin:
            bot.send_message(admin, users) 
    # the list will be sent to your telegram chat, when you activate the bot you can add the list manually
    
    bot.polling()
    

    You can also create a class and save every chat id as an object

    import telebot
    from random import choice
    
    TOKEN = ''
    bot = telebot.TeleBot(TOKEN)
    
    admin = # your chat id
    users = []
    
    class Userbot: # The class User is already in the pyTelegramBotAPI
        def __init__(self, msg):
            self.id = msg.chat.id
            self.username = '@' + msg.from_user.username
    
        def contestWinner(self):
            text = f'Hi {self.username}, you have win!!!'
            bot.send_message(self.id, text)
    
    
    
    @bot.message_handler(commands=['start'])
    def start(msg):
        bot.send_message(msg.chat.id, 'Welcome!')
        for el in users: 
            if msg.chat.id not in el.id:
                users.append(Userbot(msg))
    # you can't type 'if msg.chat.id not in users.id' because only the object inside the list can use the method id
    
    
    @bot.message_handler(commands=['extract']) # another way to use the list
    def extract(msg):
        if msg.chat.id == admin:
            winner = choice(users)
            winner.contestWinner()
    
    
    @bot.message_handler(commands=['unsubscribe'])
    def sendAtAll(msg):
        for el in users: 
            if msg.chat.id == el.id:
                del users[el]
        # only if the user inside the object is the same as the user that has sent the message the object will be deleated
        bot.send_message(msg.chat.id, "If you want to receive the notification click /start")
    
    
    @bot.message_handler(commands=['save_user_list'])
    def sendAtAll(msg):
        if msg.chat.id == admin:
            bot.send_message(admin, users)
    
    bot.polling()
    

    Apologise for my terrible english

    Login or Signup to reply.
  2. It is very easy, just use a simple database.
    MongoDB is the best choose in my opinion.
    Create an account on it and follow this tutorial.

    First get the user_id

    userid1 = str(update.message.chat_id)
    

    Then store it into the database

        import pymongo
        from pymongo import MongoClient
    
        cluster = MongoClient("mongodb+srv://<user>:<password>@cluster0.uubct.mongodb.net/users?retryWrites=true&w=majority")
        db = cluster["users"]
        collection = db["users"]
    
        results = collection.find({"_id": int(userid1)})
    
        if results.count() == 0:
            print("post")
            
            post = {"_id": int(userid1)}
            collection.insert_one(post)
    
        else:
            print("User already in the database!")
    

    For getting it you need to use the find() method.

    results = collection.find()
    
        for result in results:
            var1 = (result["_id"])
    
            print(var1)
            
            context.bot.send_message(chat_id=prova,
                                     text = "Hi")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search