使用discord.py识别并保存特定渠道中的Spotify链接

问题描述

我正在尝试对discord机器人进行编程,该机器人会扫描公会中的某个频道以查找Spotify链接,然后将其保存到文件中,然后再将其发送到Web服务器。理想情况下,发布的最新链接应该在顶部,然后向下。

我遇到的麻烦是查找并保存链接。我已经看到了一些用正则表达式检测URL的方法,尽管这些方法似乎是用于删除邀请链接,但不适用于我的目的。

这与discord.py有关吗?

解决方法

您可以使用TextChannel.history遍历整个频道,并使用正则表达式或类似方法查找链接并将其保存在列表中:

import discord
from discord.ext import commands
import re

client = discord.ext.commands.Bot(command_prefix = "!")

def saveToFile(links):
    with open ("Output.txt","a") as f:
        for link in links:
            f.write(link + "\n")

@client.command()
async def getLinks(ctx):
    links = []
    channel = client.get_channel(1234567890)
    async for message in channel.history():
        if "https://open.spotify.com/" in message.content:
            message = message.content
            message = re.search("((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-]*)?\??(?:[-\+=&;%@.\w]*)#?(?:[\w]*))?)",message).group(0)
            links.append(message)
    saveToFile(links)

client.run(your_bot_token)

正则表达式适用于任何链接,您可以根据需要对其进行调整,使其仅适用于Spotify链接。