python 写一个简单的 telegram bot (电报机器人)

一、过程

  1. 我是先看视频教程。因为官方文档太长了,太乱了,而且我也没耐心。
  2. 代码部分其实很好理解,难度不大。 
  3. 比较麻烦的是,需要与tg客户端进行交互, 操作比较多,看视频教程其实是个好选择。

二、代码 

# -*- coding: UTF-8 -*-
# 2024年7月9日, 0009 14:11

from telegram import Update # pip install python-telegram-bot
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

 

"""
 

1. Telegram Desktop --> 搜索 botfather --> start -- > 输入 newbot
2. @dragon_dance_bot  : t.me/dragon_dance_bot 
3. token: xxx
4. more doc: https://core.telegram.org/bots/api

start - start the bot
help - show some help message
custom - some other command. 

"""

token = "xxx"
bot_username = "@dragon_dance_bot"


# commands   一些命令!  目前就3个命令
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("这是一条欢迎消息!")


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("帮助信息: 请输入 xxx")


async def custom_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("这是一条私人定制消息!")


# 处理相应的工具函数!
def handle_response(text: str) -> str:
    clean_text = text.lower().strip()

    if "hello" in clean_text:
        return "Hi!"
    elif "nice" in clean_text:
        return "Real Nice!"
    else:
        return "Ooooo, What?"


# 这里的这个变量名, update,  我觉得很奇怪。 它其实是一个消息传递的中间件。
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    message_type = update.message.chat.type  # 是群聊,还是私聊
    text =  update.message.text

    # 打印一些内容
    print(f"User id: {update.message.chat.id} in {message_type}, {text}")

    if message_type == "group":
        if bot_username in text:
            new_text = text.replace(bot_username, "").strip()
            response = handle_response(new_text)
        else:
            return
    else:
        response = handle_response(text)

    print("Bot 回复的消息是: ", response)
    await update.message.reply_text(response) # 这里才是真正的回复消息。


# log  日志记录一些消息
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f"Update {update}  caused by {context.error}")


if __name__ == '__main__':
    print("Start bot server......")
    app = Application.builder().token(token).build()

    # commands 一些命令
    app.add_handler(CommandHandler("start", start_command))
    app.add_handler(CommandHandler("help", help_command))
    app.add_handler(CommandHandler("custom", custom_command))


    # Message 消息处理相关的命令!
    app.add_handler(MessageHandler(filters.TEXT, handle_message))

    # Errors
    app.add_error_handler(error)

    # other stuff
    print("Read user message........")
    app.run_polling(poll_interval=1)   # 每1秒读取一次用户的消息!


3. 这里就是做一个简短的记录。下次用起来比较方便一些。

4. 部署问题

heroku.com  注册登录不方便,需要各种验证。

replit.com  环境配置太恶心了,只能使用 poetry. 
poetry 这个名字是挺好听,用起来也是很垃圾,太恶心。

所以,部署的问题,目前搁置。

Telegram Bot是一种用于自动化交互的第三方应用,它可以在Telegram聊天平台上代表用户或服务发送消息、处理命令等。如果你想要创建一个私聊中发送欢迎消息并自动置顶的功能,你可以这样做: 1. 首先,确保你已经有一个Telegram Bot并获取了Bot API密钥。你可以在Telegram开发者平台设置中创建一个Bot。 2. 使用Python的`python-telegram-bot`库,这是一个方便操作Telegram API的库。安装它可以用pip命令:`pip install python-telegram-bot` 3. 在编代码时,导入必要的模块: ```python from telegram.ext import Updater, CommandHandler, MessageHandler, Filters ``` 4. 创建一个函数来发送欢迎消息并在私聊中置顶: ```python def send_welcome_and_pin(update, context): chat_id = update.effective_chat.id message_text = "欢迎您!这里是您的个性化欢迎信息..." # 发送欢迎消息 context.bot.send_message(chat_id=chat_id, text=message_text) # 尝试置顶,如果权限允许(管理员或者超级群组) try: context.bot.pin_chat_message( chat_id, context.bot.get_updates()[-1].message.message_id, # 最新消息ID disable_notification=True # 可选,关闭通知 ) except TelegramError as e: print(f"无法置顶消息: {e}") # 添加消息处理器 updater = Updater(token='YOUR_BOT_TOKEN', use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(MessageHandler(Filters.text & (~Filters.command), send_welcome_and_pin)) ``` 5. 替换 `'YOUR_BOT_TOKEN'` 为你实际的Bot API密钥,并确保在用户私聊中运行此功能。可以将这个功能放在`CommandHandler`之前,使其在接收到非特定命令的消息时触发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

waterHBO

老哥,支持一下啊

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值