
目录:
- 什么是 Telegram 机器人?
- 先决条件
- 在 Telegram 上创建一个机器人
- 设置Python环境
- 编写机器人代码
- 部署机器人
- 结论
1. 什么是 Telegram 机器人?
机器人是完全在 Telegram 应用程序中运行的小型应用程序。用户通过灵活的界面与机器人交互,这些界面可以支持任何类型的任务或服务。
您可以在官方文档中阅读有关机器人的更多信息:
机器人
Telegram 机器人 API
2. 前提条件
在深入创建机器人之前,您需要以下内容:
-
Telegram 帐户:您可以通过在手机上下载 Telegram 应用程序轻松创建一个帐户。
-
已安装 Python:我们将使用 Python 3,因此请确保它已安装在您的计算机上。 下载链接
-
基本 Python 知识:了解 Python 语法和包将帮助您浏览代码。我可以推荐这本书《Automate the Boring Stuff with Python》
-
BotFather 访问:BotFather 是一个内置的 Telegram 机器人,可帮助您管理和创建新机器人。
-
VS Code(可选):我用它来编写我的机器人。但请随意选择任何其他编辑器。但我建议使用这个。
在这里您可以下载最新版本的 VS Code,这里是有关如何为 Python 设置它的说明。
3. 在 Telegram 上创建一个机器人
要创建自己的机器人,您需要使用BotFather,这是在 Telegram 上注册和管理机器人的官方工具。
步骤:
- 打开 Telegram 并搜索 BotFather 机器人。 (在搜索菜单中输入@botfather)
- 输入 /start 开始与 BotFather 聊天。
- 通过输入 /newbot 创建一个新机器人。
- 系统将提示您提供机器人的名称。输入一个唯一的名称(例如,Hello World)。
- BotFather 将询问机器人的用户名。用户名必须以“bot”结尾(例如 HelloWorldBot)。
- 完成这些步骤后,BotFather 会给您一个令牌。该令牌至关重要,因为它可以验证您的机器人并允许您与 Telegram 的 API 进行交互。
重要:将您的代币保密,不要公开分享!
4. 设置Python环境
接下来,我们需要设置 Python 环境来与 Telegram API 交互。我们将使用 python-telegram-bot 库,它提供了一个简单易用的界面来开发 Telegram 机器人。
步骤:
安装 python-telegram-bot 库:
运行以下命令来安装必要的库:
1 | pip install python-telegram-bot
|
登录后复制
创建一个新的 Python 文件: 您可以将其命名为 my_bot.py 之类的名称来保存机器人的代码。
5. 编写机器人代码
现在我们的环境已经准备好了,让我们来编写机器人代码。
示例代码
这是一个响应 /start 和 /help 命令的基本机器人:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
# Enable logging
logging.basicConfig(format= '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ,
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a start function to respond to the /start command
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text( 'Hello! I am your bot. How can I help you today?' )
# Define a help function to respond to the /help command
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text( 'You can use the following commands:\n/start - Start the bot\n/help - Get help' )
def main():
# Create the application and pass the bot token
application = ApplicationBuilder().token( 'YOUR_BOT_TOKEN_HERE' ).build()
# Add command handlers for /start and /help
application.add_handler(CommandHandler( "start" , start))
application.add_handler(CommandHandler( "help" , help_command))
# Start the bot and run it until manually stopped
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == '__main__' :
main()
|
登录后复制
解释:
-
导入:我们导入 telegram 和 telegram.ext 模块来构建我们的机器人。这些提供了与 Telegram API 交互所需的类和函数。
-
日志记录:启用日志记录以跟踪事件和错误。
-
启动和帮助命令:我们定义了两个函数(start 和 help_command),它们在用户触发相应命令时发送消息。
-
令牌: 将“YOUR_BOT_TOKEN_HERE”替换为您从 BotFather 收到的令牌。
-
轮询: 机器人使用轮询不断检查新消息并在新消息到来时做出响应。
运行机器人:
- 将代码中的占位符令牌替换为您的机器人的令牌。
- 运行你的Python脚本:
您的机器人现已启动并运行!打开 Telegram,向机器人发送 /start 或 /help 命令,它就会响应。
6. 部署机器人
在本地计算机上运行机器人非常适合测试,但如果您希望它 24/7 可用怎么办?为此,您可以将机器人部署到服务器或云服务。
常见部署选项:
-
Heroku: 一个免费的云平台,您可以在其中托管您的机器人。
-
AWS(亚马逊网络服务):可扩展性更强,但可能需要初学者进行一些设置。
-
VPS(虚拟专用服务器):让您完全控制您的服务器。
-
PythonAnywhere: 适合初学者的免费选项。
每个平台都提供了部署 Python 应用程序的独特方法。您可以按照特定于您选择的服务的部署教程进行操作。
七、结论
恭喜!您已经使用 Python 成功创建了一个基本的 Telegram 机器人。您学会了如何:
- 使用 BotFather 设置 Telegram 机器人。
- 编写Python代码来处理命令。
- 在本地运行机器人并在 Telegram 上与其交互。
接下来,我建议您学习 python-telegram-bot 中的示例机器人
这是一个系列文章。在接下来的文章中,我将解释如何在 PythonAnywhere 上托管机器人,如何在您自己的 Raspberry PI 服务器上托管机器人,以及如何创建更复杂的机器人。
以上是在 Python 上创建 Telegram 机器人的详细内容。更多信息请关注PHP中文网其他相关文章!