所以我用discord.py库做了一个python discord bot,它工作得很好,直到我试着用slashcommands打开代码的一个版本.我在日志(log)里一点错误都没有... 以下是我的代码:

100

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)

这个机器人运行在Repl.it上,由Uptime Robot维护,顺便说一句,提前谢谢你!

推荐答案

我看到您仍在使用CTX来执行斜杠命令.

@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(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))

要使此功能正常工作,您只需导入以下内容:

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

希望这个能帮上忙!如果是,请将此答案标记为已接受:)

Python相关问答推荐

指示组内的rejected_time是否在creation_timestamp后5分钟内

如何防止Plotly在输出到PDF时减少行中的点数?

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

即使在可见的情况下也不相互作用

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

优化pytorch函数以消除for循环

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

所有列的滚动标准差,忽略NaN

使用NeuralProphet绘制置信区间时出错

如何并行化/加速并行numba代码?

Django admin Csrf令牌未设置

如何在达到end_time时自动将状态字段从1更改为0

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

python—telegraph—bot send_voice发送空文件

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

如何过滤组s最大和最小行使用`transform`'

在电影中向西北方向对齐""

Python将一个列值分割成多个列,并保持其余列相同

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行

替换包含Python DataFrame中的值的<;