telegram_bot.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. import requests
  3. from dotenv import load_dotenv
  4. from flask import Flask, request
  5. from embedchain import App
  6. app = Flask(__name__)
  7. load_dotenv()
  8. bot_token = os.environ["TELEGRAM_BOT_TOKEN"]
  9. chat_bot = App()
  10. @app.route("/", methods=["POST"])
  11. def telegram_webhook():
  12. data = request.json
  13. message = data["message"]
  14. chat_id = message["chat"]["id"]
  15. text = message["text"]
  16. if text.startswith("/start"):
  17. response_text = (
  18. "Welcome to Embedchain Bot! Try the following commands to use the bot:\n"
  19. "For adding data sources:\n /add <data_type> <url_or_text>\n"
  20. "For asking queries:\n /query <question>"
  21. )
  22. elif text.startswith("/add"):
  23. _, data_type, url_or_text = text.split(maxsplit=2)
  24. response_text = add_to_chat_bot(data_type, url_or_text)
  25. elif text.startswith("/query"):
  26. _, question = text.split(maxsplit=1)
  27. response_text = query_chat_bot(question)
  28. else:
  29. response_text = "Invalid command. Please refer to the documentation for correct syntax."
  30. send_message(chat_id, response_text)
  31. return "OK"
  32. def add_to_chat_bot(data_type, url_or_text):
  33. try:
  34. chat_bot.add(data_type, url_or_text)
  35. response_text = f"Added {data_type} : {url_or_text}"
  36. except Exception as e:
  37. response_text = f"Failed to add {data_type} : {url_or_text}"
  38. print("Error occurred during 'add' command:", e)
  39. return response_text
  40. def query_chat_bot(question):
  41. try:
  42. response = chat_bot.chat(question)
  43. response_text = response
  44. except Exception as e:
  45. response_text = "An error occurred. Please try again!"
  46. print("Error occurred during 'query' command:", e)
  47. return response_text
  48. def send_message(chat_id, text):
  49. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  50. data = {"chat_id": chat_id, "text": text}
  51. requests.post(url, json=data)
  52. if __name__ == "__main__":
  53. app.run(host="0.0.0.0", port=8000, debug=False)