一、什么是tg机器人?
telegram(以下简称tg)是一款非常流行的即时通讯软件,tg机器人就是可自动执行指定任务的程序,可以为用户提供一些便捷服务。
二、tg机器人的功能
tg机器人的功能非常强大,可以实现以下任务:
1.提醒用户定时任务
import schedule import time def job(): print("I'm working...") schedule.every(10).seconds.do(job) while True: schedule.run_pending() time.sleep(1)
使用schedule库可以很方便实现定时任务,本示例每10秒执行一次job函数。
2.天气查询
import requests def get_weather(city_name): url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city_name response = requests.get(url) weather_data = response.json()['data'] if weather_data: city = weather_data['city'] forecast = weather_data['forecast'][0] date = forecast['date'] high_temperature = forecast['high'] low_temperature = forecast['low'] weather = forecast['type'] tips = weather_data['ganmao'] return f"{city}
{date}
天气{weather},最高气温{high_temperature},最低气温{low_temperature}
温馨提示:{tips}" else: return '城市名输入有误'
使用requests库可以方便地向API发送请求,本示例将央视天气API中的数据解析为文字显示。
3.机器人回复电影信息
import requests def get_movie_info(name): url = f'https://api.douban.com/v2/movie/search?q={name}' data = requests.get(url).json() if data['subjects']: movie = data['subjects'][0] title = movie['title'] rating = movie['rating']['average'] cover_url = movie['images']['small'] summary = movie['summary'] return f"封面
{title}评分:{rating}
{summary}"
使用requests库可以方便地向API发送请求,本示例将豆瓣电影API中的数据解析为文字和图片显示。
三、如何创建tg机器人?
创建机器人前需要在tg中找到BotFather,发送/start并按照提示完成创建即可得到token。
使用python编程,可以使用第三方库python-telegram-bot方便地操作机器人,安装:
pip install python-telegram-bot
四、如何使用python编写tg机器人?
接下来介绍一个简单的tg机器人,实现发送文本消息、图片消息和回应命令等基本功能。
import telegram from telegram.ext import CommandHandler, MessageHandler, Filters, Updater def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="欢迎使用机器人,发送/help获取帮助") def help(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="/start - 启动机器人
/help - 帮助信息
/pic - 发送图片") def pic(update, context): context.bot.send_photo(chat_id=update.effective_chat.id, photo=open('image.jpg', 'rb')) def text(update, context): text = update.message.text if text.startswith('/'): return context.bot.send_message(chat_id=update.effective_chat.id, text=f"您发送了{text}") def main(): updater = Updater(token='XXXXXXXXXXXXXXXXXXXXXXXXXXX', use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("pic", pic)) dp.add_handler(MessageHandler(Filters.text & ~Filters.command, text)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
1.创建机器人
从BotFather那得到token并创建机器人,并且将token添加到代码中。
2.调用telegram API
导入telegram库,使用Upader实例,Dispatcher添加CommandHandler和MessageHandler,根据不同的command和text发送不同的内容。
3.运行程序
使用start_polling()暂时启动机器人,使用idle()使机器人保持运行。
五、tg机器人的作用和未来
tg机器人可以帮助我们实现很多便捷的服务,比如提醒、查询、推送等等,未来可能会有更多人性化的功能加入进来,可以为我们生活和工作提供更多的帮助。
原创文章,作者:AHYFG,如若转载,请注明出处:https://www.506064.com/n/334058.html