【问题标题】:python telegrambot store chat idpython电报机器人商店聊天ID
【发布时间】:2021-07-09 12:50:16
【问题描述】:

我想知道如何存储/读出用户聊天 ID 以便以后向他们发送消息。

例如,用户正在添加我的电报机器人并向他发送消息。 稍后在我的程序中,当某个特定情况发生时,我想向特定用户发送消息。

举个简单的例子,我有这个代码:

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

我知道如何处理对用户在电报聊天中发送的命令的响应,但不知道如何在没有先收到命令的情况下向用户发送消息。我认为因此我需要有一种方法来首先存储用户聊天 ID,以便稍后在发送消息时引用该 ID。

关键是我想稍后将我的程序编译为 .exe 并将其发送给一些朋友,它也应该适用于他们。

【问题讨论】:

  • 您需要将 ID 保存在某处、某种数据库或 API。
  • 我想是的。我只是不知道怎么做:-)
  • 这是 Stackoverflow 上的一个问题。尝试在谷歌上搜索数据库教程,或者一些关于在 .exe 中保存数据的教程。应该有足够的起点。

标签: python telegram telegram-bot py-telegram-bot-api


【解决方案1】:

这很容易,只需使用一个简单的数据库。 在我看来,MongoDB 是最好的选择。 在上面创建一个帐户并关注this tutorial

首先获取user_id

userid1 = str(update.message.chat_id)

然后存入数据库

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

要获取它,您需要使用 find() 方法。

results = collection.find()

    for result in results:
        var1 = (result["_id"])

        print(var1)
        
        context.bot.send_message(chat_id=prova,
                                 text = "Hi")

【讨论】:

    【解决方案2】:

    您可以简单地将 id 添加到列表中,而无需任何第三方包装

    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()
    

    您还可以创建一个类并将每个聊天 id 保存为一个对象

    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()
    

    为我糟糕的英语道歉

    【讨论】:

      猜你喜欢
      • 2019-09-13
      • 2017-05-01
      • 1970-01-01
      • 2018-01-13
      • 2022-12-11
      • 2019-07-25
      • 2017-01-06
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多