discord.py 4.0 KB

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