繁体   English   中英

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

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

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

我遇到的问题是查找和保存链接。 我已经看到了一些使用正则表达式检测 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 链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM