discord.py 4.2 KB

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