python Bot 创建邀请但不会告诉我成员已加入

问题描述 投票:0回答:0

我正在尝试创建一个 Telegram 机器人,为特定组生成邀请链接。我的机器人成功创建了一个邀请并将其分配给以下用户,但是,它没有告诉我有多少用户加入了,而是无论我尝试编辑代码多少次,它总是告诉我“无法获得邀请链接”。我加入了另一个帐户,但它执行了相同的响应。

import logging

导入sqlite3 导入 tracemalloc

版本 23.1

from telegram import ForceReply, Update, version as TG_VER 来自 telegram.error import BadRequest, TelegramError 从 telegram.ext 导入 ( 应用, 命令处理器, 上下文类型, 回调上下文, 消息处理程序, 过滤器 )

尝试: 从电报导入version_info 除了导入错误: version_info = (0, 0, 0, 0, 0)

if version_info < (20, 0, 0, "alpha", 1): raise RuntimeError( f"This example is not compatible with your current PTB version {TG_VER}. To view the " f"{TG_VER} version of this example, " f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html" )

logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) 记录器 = logging.getLogger(name)

conn = sqlite3.connect("invites_bot.db") 游标 = conn.cursor()

tracemalloc.start()

游标.执行( """ CREATE TABLE IF NOT EXISTS 邀请 ( id 整数主键自动增量, 用户 ID 整数, invite_link TEXT, members_joined 整数默认值 0, 唯一(用户 ID) ) """ )

async def start(更新:更新,上下文:ContextTypes.DEFAULT_TYPE)->无: """发出命令 /start 时发送消息。""" 用户 = update.effective_user 等待更新.message.reply_html( rf“嗨 {user.mention_html()}!”, reply_markup=ForceReply(selective=True), )

async def invite(update: Update, context: CallbackContext) -> None: """为组创建邀请链接并将其分配给用户。""" user_id = update.effective_user.id cursor.execute("SELECT * FROM invites WHERE user_id=?", (user_id,)) invite_data = cursor.fetchone() 如果邀请数据: invite_link = invite_data[2] await update.message.reply_html(f"您已经有一个邀请链接:{invite_link}") 别的: group_id = -5 # 5 是我的用户 ID 尝试: invite_link = await context.bot.create_chat_invite_link(group_id) 除了 BadRequest 为 e: 如果 e.message == '超出防洪控制': await update.message.reply_text("创建邀请链接失败,请稍后重试。") 返回 别的: 提高e

    cursor.execute(
        "INSERT INTO invites (user_id, invite_link, members_joined) VALUES (?, ?, ?)",
        (user_id, invite_link.invite_link, 0)
    )
    conn.commit()
    await update.message.reply_html(f"Here's your invite link: {invite_link.invite_link}")

async def 帮助(更新:更新,上下文:ContextTypes.DEFAULT_TYPE)-> 无: """发出命令 /help 时发送消息。""" await update.message.reply_text("请使用以下命令继续")

async def stats(更新:更新,上下文:CallbackContext)->无: """跟踪加入邀请链接的成员数量。""" user_id = update.effective_user.id cursor.execute("SELECT * FROM invites WHERE user_id=?", (user_id,)) invite_data = cursor.fetchone() 如果邀请数据: invite_link = invite_data[2] 尝试: chat_id = int(invite_link.split("/")[-1]) 除了(ValueError,IndexError): await update.message.reply_text("获取邀请链接失败。") 返回

    try:
        chat = await context.bot.get_chat(chat_id)
    except TelegramError as tge:
        await update.message.reply_text(f"Failed to get chat information:\n\n{tge.message}")
        return

    if chat.type != "supergroup":
        await update.message.reply_text("The invite link is not for a supergroup.")
        return

    members_joined = invite_data[3]
    if members_joined == 0:
        await update.message.reply_text("No one has joined your invite link yet.")
    else:
        await update.message.reply_html(f"You have invited {members_joined} member{'s' if members_joined > 1 else ''}.")
else:
    await update.message.reply_text("You don't have an invite link. Use /invite")

def main() -> 无: """启动机器人。"""

application = Application.builder().token("my_user_id").build()


application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("invite", invite))
application.add_handler(CommandHandler("stats", stats))
application.add_handler(CommandHandler("help", help))


application.run_polling()

if name == "main": 主要()

我使用了成功运行的 /start 命令。如果用户首先使用统计信息而不是邀请,机器人会成功执行,但它无法告诉我 members_joined。

python telegram telegram-bot python-telegram-bot py-telegram-bot-api
© www.soinside.com 2019 - 2024. All rights reserved.