Search code examples
pythondiscorddiscord.pycommandbots

Why isn't my discord bot answering when I type the command?


So im doing a python discord bot using discord.py library and it worked perfectly until I tried to switch on a version of the code using the slashcommands. I have no error at all in the logs... Here is my code :

main.py

import discord
from discord.ext import commands
from datetime import date, timedelta
from icalendar import Calendar
from keep_alive import keep_alive
from config import TOKEN, CHANNEL_ID

keep_alive()

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='$', intents=intents)


@client.event
async def on_ready():
  print(f'We have logged in as {client.user}')


@client.event
async def on_message(message):
  # Ignore messages from the bot itself
  if message.author == client.user:
    return

  await client.process_commands(message)


@client.command()
async def date(ctx):
  todaydate = date.today()
  d1 = todaydate.strftime("%d/%m/%Y")
  await ctx.send('Nous sommes le ' + str(d1))


@client.command()
async def cours(ctx, *args):
  if not args:
    await ctx.send(
        "Veuillez spécifier 'today' ou 'demain' après la commande $cours.")
    return

  if args[0].lower() == 'today':
    await display_courses(ctx, date.today())
  elif args[0].lower() == 'demain':
    await display_courses(ctx, date.today() + timedelta(days=1))
  else:
    await ctx.send(
        "Argument non reconnu. Utilisez 'today' ou 'demain' après la commande $cours."
    )


async def display_courses(ctx, target_date):
  courses = []
  horaires = []
  locations = []

  e = open('Agenda/groupeD.ics', 'rb')
  ecal = Calendar.from_ical(e.read())  #Récupérer le calendar pepal

  todaydate = date.today()
  d2 = todaydate.strftime("%Y%m%d")  #Formatage de la date

  # Ajout : définir la variable datejour
  datejour = todaydate.strftime("%d/%m/%Y")

  for event in ecal.walk('VEVENT'):
    Aevent = event.get("DTSTART")
    step = Aevent.dt
    d3 = step.strftime("%Y%m%d")  #Récupération et formatage date cible
    horaire = step.strftime("%Hh%M")
    location = event.get("LOCATION")

    if d3 == d2:
      courses.append(event.get("SUMMARY"))  #Ajouter
      horaires.append(horaire)
      locations.append(location)

  e.close()

  embedVar = discord.Embed(title=f"Emploi du temps {datejour}",
                           description="Aujourd'hui vous avez : ",
                           color=0x3853B4)
  if len(courses) > 0:
    embedVar.add_field(name=courses[0],
                       value=f"{horaires[0]} en **{locations[0].lower()}**",
                       inline=False)
    if len(courses) > 1:
      embedVar.add_field(name=courses[1],
                         value=f"{horaires[1]} en **{locations[1].lower()}**",
                         inline=False)
  else:
    embedVar.add_field(name="Pas de cours",
                       value="Aucun cours pour aujourd'hui.",
                       inline=False)

  await ctx.send(embed=embedVar)


@client.command()
async def ping(ctx):
  # ... (your existing code for $ping)
  pass


# Easter egg
@client.event
async def on_message(message):
  if message.content.startswith('42'):
    embedVar = discord.Embed(
        title="42",
        description=
        "La solution à la grande question sur la vie, l'univers , et le reste, assurément...",
        color=0x3853B4)
    await message.channel.send(embed=embedVar)


client.run(TOKEN)

The bot runs on Repl.it and is maintained by UptimeRobot, btw thank you in advance !


Solution

  • I see you are still using CTX for slash commands.

    @client.command()
    async def date(ctx):
      todaydate = date.today()
      d1 = todaydate.strftime("%d/%m/%Y")
      await ctx.send('Nous sommes le ' + str(d1))
    

    however, for slash commands, you need discord.Interaction, or it wont show up as a slash command. Its not giving you an error because nothing is truley wrong with your code, just a couple module that were imported but never used (usally underlined in yellow)

    Here is the updated code for that block of code, remember to do this for all other code blocks as well.

    @client.command(name="date", description="WHATEVER_YOUR_DESCRIPTION_IS")
    async def date(interation: discord.Interaction):
      todaydate = datetime.utcnow() # Using UTC time is more reliable #compensate your timezone by using real_today = todaydate [+ or -] timedelta(hours=?)
      d1 = todaydate.strftime("%d/%m/%Y")
      await interaction.response.send_message('Nous sommes le ' + str(d1))
    

    These are the only imports you need to make this work:

    import discord
    from discord.ext import commands
    from datetime import datetime
    

    Hope this helps! If so, mark this answer as accepted :)