I'm trying to program a Discord bot that scans a channel in a guild for Spotify links, then saves them to a file which I can then beam to my webserver. Ideally the latest links posted would be on top, and descending down.
What I'm having trouble with is finding and saving the links. I've seen some methods of detecting URLs with regex, although those seem to be for deleting invite links and wouldn't work for my purposes.
Is this possible to do with discord.py?
You can iterate through the whole channel using TextChannel.history
and use regex or something similar to find the links and save them in a list:
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)
The regex will work for any link, you can adapt it to only work for Spotify links if you prefer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.