python电报机器人商店聊天ID

时间:2021-07-09 12:50:16

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

我想知道如何存储/读出用户聊天 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 并将其发送给一些朋友,它应该也适用于他们。

2 个答案:

答案 0 :(得分:0)

您可以简单地将 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()

为我糟糕的英语道歉

答案 1 :(得分:0)

很简单,只需使用一个简单的数据库。 在我看来,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")