problema con ids
Some checks failed
Update Bot / restart-bot (push) Has been cancelled
Update Bot / deploy-via-sftp (push) Has been cancelled

This commit is contained in:
2025-10-27 09:35:02 +01:00
parent 767874c246
commit d31540514a

200
main.py Normal file → Executable file
View File

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