import requests import discord from discord.ext import commands from discord.ext import tasks import secrets import time import xmltodict intents = discord.Intents.all() allowed_mentions = discord.AllowedMentions(everyone = True) bot = commands.Bot(command_prefix="$", intents=intents, allowed_mentions=allowed_mentions) url = "https://www.infodefensa.com/sitemap/lastarticles" r = requests.get(url) xml = xmltodict.parse(r.text) ultimaurl = xml['urlset']['url'][0]['loc'] #Guarda la última url del xml #viejoxml = xml['urlset']['url'][0]['loc'] #Guarda la primera url del xml al encender el bot @bot.event async def on_ready(): print(f"Bot vivo! \nUsuario: {bot.user}") await bot.user.edit(username="Pregonero") await bot.change_presence( status=discord.Status.online, activity=discord.Activity( type=discord.ActivityType.playing, name="Pregoneando")) await send_log(f"hora de inicio: {time.ctime(time.time())}") mandar_noticia.start() async def send_log(msg): #Mandar log channel = bot.get_channel(secrets.IDcanalLogs) #Canal al que se envía el log await channel.send(msg) @tasks.loop(minutes = 5) #Mandar noticias async def mandar_noticia(): global ultimaurl try: channel = bot.get_channel(secrets.IDcanalNoticias) #Canal al que se envía el mensaje r = requests.get(url) xml = xmltodict.parse(r.text) urls = [u['loc'] for u in xml['urlset']['url']] #Lista de todas las URL nuevas = [] for loc in urls: if loc == ultimaurl: break nuevas.append(loc) if nuevas: #Si el array no está vacío await channel.send(f"Atención <@&{secrets.IDrol}> hay nuevas noticias:") #Luego hay que cambiar el rol for loc in reversed(nuevas): #Recorre el array hacia atrás para mandarlas en orden. await channel.send(f"\n{loc}") ultimaurl = urls[0] #Actualizamos la url vieja except Exception as e: await send_log(f"Error: ```{e}```") @bot.command() async def noticias(ctx): rol = ctx.guild.get_role(secrets.IDrol) user = ctx.author if rol in user.roles: await user.remove_roles(rol) await ctx.send(f"Entendido {user.mention}, ya no recibirás las noticias", delete_after=10) else: await user.add_roles(rol) await ctx.send(f"Entendido {user.mention}, ahora recibirás las noticias", delete_after=10) #@tasks.loop(minutes = 5) #Mandar noticias #async def mandar_noticia(): # global viejoxml # try: # channel = bot.get_channel(secrets.IDcanalNoticias) #Canal al que se envía el mensaje # r = requests.get(url) # xml = xmltodict.parse(r.text) # nuevoxml = xml['urlset']['url'][0]['loc'] #Guarda la primera url del xml # if nuevoxml != viejoxml: #Compara las url # await channel.send(f"Atención <@&{secrets.IDrol}> hay una nueva noticia:\n{xml['urlset']['url'][0]['loc']}") #Luego hay que cambiar el rol # viejoxml = nuevoxml #Actualizamos la url vieja # except Exception as e: # await send_log(f"Error: ```{e}```") if __name__ == '__main__': bot.run(secrets.TOKEN)