python - 电报机器人识别 URL
问题描述
我正在创建我的第一个 Telegram 机器人。我希望机器人过滤仅查找 URL 的文本,并在找到时触发。
例如,如果有人在聊天中键入“www.google.com”,我希望机器人将其识别为 URL,然后执行 X 操作。我尝试过滤单词以获得准确的 URL,但我做错了。
我正在尝试,Filters.entity(URL)
但我无法制作完整的必要代码。
这是实际的机器人代码:
import logging
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters
import os
import random
import requests
TOKEN = "XXXXX"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def coin(update, context):
''' ⚪️/⚫️ Moneda
Genera un número elatorio entre 1 y 2.
'''
cid=update.message.chat_id
msg="⚫️ Cara" if random.randint(1,2)==1 else "⚪️ Cruz"
# Responde directametne en el canal donde se le ha hablado.
update.message.reply_text(msg)
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def links(update, context):
"""Echo the user message."""
url = str(update.message.text)
if url.lower() == '*morning*':
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(TOKEN, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("coin", coin))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.entity(URL), links))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN,
webhook_url="XXXXX/" + TOKEN)
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
解决方案
dp.add_handler(MessageHandler(Filters.entity(URL), links))
把这个改成这个->
dp.add_handler(MessageHandler(Filters.entity('url'), links))
禁用您对普通文本处理程序的其他回复.. 因为该功能将您的链接视为普通文本
推荐阅读
- c# - Razor 页面登录表单在输入字段内添加图标
- c# - 无法将 TextBox 设置为焦点
- firebase - Firebase 聊天 - 需要建议
- pandas - 格式化 Python Pandas 输出以删除标题字符
- c# - 在 C# WebBrowser 控件中单击编程按钮
- html - 如何使用单独的 span 标签处理 SEO
- java - 如何配置苹果推送通知?
- tinymce - 摆脱 TinyMCE 插入文本的多余元素
- reactjs - 如何为返回 ListItem 并具有多个道具的 React Native 组件编写单元测试。我正在努力这样做。有什么建议么?
- javascript - 对单个数组元素进行数学运算比在 forEach 循环中进行运算更快?