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

Identify and save Spotify links in specific channel with discord.py

我正在尝试编写一个 Discord 机器人程序,该机器人扫描公会中的频道以获取 Spotify 链接,然后将它们保存到一个文件中,然后我可以将该文件传送到我的网络服务器。理想情况下,最新发布的链接应该在顶部,然后向下。

我遇到的问题是查找和保存链接。我见过一些使用正则表达式检测 URL 的方法,尽管这些方法似乎是为了删除邀请链接而对我的目的不起作用。

这可能与 discord.py 相关吗?

您可以使用 TextChannel.history 遍历整个频道并使用正则表达式或类似的东西找到 link 并将它们保存在列表中:

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)

正则表达式适用于任何 link,如果您愿意,您可以将其调整为仅适用于 Spotify link。