discord_bot.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. import discord
  3. from discord.ext import commands
  4. from dotenv import load_dotenv
  5. from embedchain import App
  6. load_dotenv()
  7. intents = discord.Intents.default()
  8. intents.message_content = True
  9. bot = commands.Bot(command_prefix="/ec ", intents=intents)
  10. root_folder = os.getcwd()
  11. def initialize_chat_bot():
  12. global chat_bot
  13. chat_bot = App()
  14. @bot.event
  15. async def on_ready():
  16. print(f"Logged in as {bot.user.name}")
  17. initialize_chat_bot()
  18. @bot.event
  19. async def on_command_error(ctx, error):
  20. if isinstance(error, commands.CommandNotFound):
  21. await send_response(ctx, "Invalid command. Please refer to the documentation for correct syntax.")
  22. else:
  23. print("Error occurred during command execution:", error)
  24. @bot.command()
  25. async def add(ctx, data_type: str, *, url_or_text: str):
  26. print(f"User: {ctx.author.name}, Data Type: {data_type}, URL/Text: {url_or_text}")
  27. try:
  28. chat_bot.add(data_type, url_or_text)
  29. await send_response(ctx, f"Added {data_type} : {url_or_text}")
  30. except Exception as e:
  31. await send_response(ctx, f"Failed to add {data_type} : {url_or_text}")
  32. print("Error occurred during 'add' command:", e)
  33. @bot.command()
  34. async def query(ctx, *, question: str):
  35. print(f"User: {ctx.author.name}, Query: {question}")
  36. try:
  37. response = chat_bot.query(question)
  38. await send_response(ctx, response)
  39. except Exception as e:
  40. await send_response(ctx, "An error occurred. Please try again!")
  41. print("Error occurred during 'query' command:", e)
  42. @bot.command()
  43. async def chat(ctx, *, question: str):
  44. print(f"User: {ctx.author.name}, Query: {question}")
  45. try:
  46. response = chat_bot.chat(question)
  47. await send_response(ctx, response)
  48. except Exception as e:
  49. await send_response(ctx, "An error occurred. Please try again!")
  50. print("Error occurred during 'chat' command:", e)
  51. async def send_response(ctx, message):
  52. if ctx.guild is None:
  53. await ctx.send(message)
  54. else:
  55. await ctx.reply(message)
  56. bot.run(os.environ["DISCORD_BOT_TOKEN"])