discord.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import argparse
  2. import logging
  3. import os
  4. import discord
  5. from discord import app_commands
  6. from discord.ext import commands
  7. from .base import BaseBot
  8. intents = discord.Intents.default()
  9. intents.message_content = True
  10. client = discord.Client(intents=intents)
  11. tree = app_commands.CommandTree(client)
  12. # Invite link example
  13. # https://discord.com/api/oauth2/authorize?client_id={DISCORD_CLIENT_ID}&permissions=2048&scope=bot
  14. class DiscordBot(BaseBot):
  15. def __init__(self, *args, **kwargs):
  16. BaseBot.__init__(self, *args, **kwargs)
  17. def add_data(self, message):
  18. data = message.split(" ")[-1]
  19. try:
  20. self.add(data)
  21. response = f"Added data from: {data}"
  22. except Exception:
  23. logging.exception(f"Failed to add data {data}.")
  24. response = "Some error occurred while adding data."
  25. return response
  26. def ask_bot(self, message):
  27. try:
  28. response = self.query(message)
  29. except Exception:
  30. logging.exception(f"Failed to query {message}.")
  31. response = "An error occurred. Please try again!"
  32. return response
  33. def start(self):
  34. client.run(os.environ["DISCORD_BOT_TOKEN"])
  35. # @tree decorator cannot be used in a class. A global discord_bot is used as a workaround.
  36. @tree.command(name="question", description="ask embedchain")
  37. async def query_command(interaction: discord.Interaction, question: str):
  38. await interaction.response.defer()
  39. member = client.guilds[0].get_member(client.user.id)
  40. logging.info(f"User: {member}, Query: {question}")
  41. try:
  42. answer = discord_bot.ask_bot(question)
  43. if args.include_question:
  44. response = f"> {question}\n\n{answer}"
  45. else:
  46. response = answer
  47. await interaction.followup.send(response)
  48. except Exception as e:
  49. await interaction.followup.send("An error occurred. Please try again!")
  50. logging.error("Error occurred during 'query' command:", e)
  51. @tree.command(name="add", description="add new content to the embedchain database")
  52. async def add_command(interaction: discord.Interaction, url_or_text: str):
  53. await interaction.response.defer()
  54. member = client.guilds[0].get_member(client.user.id)
  55. logging.info(f"User: {member}, Add: {url_or_text}")
  56. try:
  57. response = discord_bot.add_data(url_or_text)
  58. await interaction.followup.send(response)
  59. except Exception as e:
  60. await interaction.followup.send("An error occurred. Please try again!")
  61. logging.error("Error occurred during 'add' command:", e)
  62. @tree.command(name="ping", description="Simple ping pong command")
  63. async def ping(interaction: discord.Interaction):
  64. await interaction.response.send_message("Pong", ephemeral=True)
  65. @tree.error
  66. async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:
  67. if isinstance(error, commands.CommandNotFound):
  68. await interaction.followup.send("Invalid command. Please refer to the documentation for correct syntax.")
  69. else:
  70. logging.error("Error occurred during command execution:", error)
  71. @client.event
  72. async def on_ready():
  73. # TODO: Sync in admin command, to not hit rate limits.
  74. # This might be overkill for most users, and it would require to set a guild or user id, where sync is allowed.
  75. await tree.sync()
  76. logging.debug("Command tree synced")
  77. logging.info(f"Logged in as {client.user.name}")
  78. def start_command():
  79. parser = argparse.ArgumentParser(description="EmbedChain DiscordBot command line interface")
  80. parser.add_argument(
  81. "--include-question",
  82. help="include question in query reply, otherwise it is hidden behind the slash command.",
  83. action="store_true",
  84. )
  85. global args
  86. args = parser.parse_args()
  87. global discord_bot
  88. discord_bot = DiscordBot()
  89. discord_bot.start()
  90. if __name__ == "__main__":
  91. start_command()