Nicolás Larenas commited on
Commit
56ce1d2
·
verified ·
1 Parent(s): 5f7447e

Update discord_bot.py

Browse files
Files changed (1) hide show
  1. discord_bot.py +20 -80
discord_bot.py CHANGED
@@ -1,108 +1,48 @@
1
- # discord_bot.py
2
-
3
  import discord
4
  import os
5
  import asyncio
6
  from discord.ext import commands, tasks
7
  from dotenv import load_dotenv
8
- from ai_model import query_ai_model
9
- from config import (
10
- SYSTEM_INSTRUCTION,
11
- MODEL_NAME,
12
- MODEL_VISION_NAME,
13
- DEFAULT_MAX_OUTPUT_TOKENS,
14
- DEFAULT_TEMPERATURE,
15
- DEFAULT_TOP_P,
16
- DEFAULT_TOP_K,
17
- DEFAULT_STOP_SEQUENCES,
18
- )
19
- import logging
20
-
21
- # Configure logging
22
- logging.basicConfig(level=logging.ERROR)
23
 
24
  # Load environment variables
25
  load_dotenv()
26
 
27
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN")
28
- if not DISCORD_TOKEN:
29
- raise ValueError("DISCORD_TOKEN is not set. Please provide your Discord bot token.")
30
-
31
  ALLOWED_CHANNELS = os.environ.get("ALLOWED_CHANNELS", "").split(",")
32
  HUGGING_FACE_SPACE_URL = os.environ.get("HUGGING_FACE_SPACE_URL")
33
 
34
  # Configure Discord bot
35
  intents = discord.Intents.default()
36
- intents.message_content = True # Ensure the bot can read message content
37
  bot = commands.Bot(command_prefix="!", intents=intents)
38
 
39
- # Store conversation histories per user
40
- user_histories = {}
41
-
42
  # On bot ready
43
  @bot.event
44
  async def on_ready():
45
  print(f"{bot.user} has connected to Discord!")
46
- keep_gradio_awake.start() # Start the task to keep the Gradio app awake
47
-
48
- # Handle messages
49
- @bot.event
50
- async def on_message(message):
51
- # Ignore messages from bots
52
- if message.author.bot:
53
- return
54
 
55
- # Check if the message is in an allowed channel
56
- if ALLOWED_CHANNELS and str(message.channel.id) not in ALLOWED_CHANNELS:
 
 
 
57
  return
58
-
59
- # Process commands (e.g., if you have other commands starting with '!')
60
- if message.content.startswith('!'):
61
- await bot.process_commands(message)
62
- return
63
-
64
- # Get user's conversation history
65
- user_id = message.author.id
66
- history = user_histories.get(user_id, [])
67
-
68
- # Respond to the message
69
- async with message.channel.typing():
70
- try:
71
- # Call the AI model
72
- assistant_reply = await query_ai_model(
73
- message.content,
74
- history=history,
75
- max_output_tokens=DEFAULT_MAX_OUTPUT_TOKENS,
76
- temperature=DEFAULT_TEMPERATURE,
77
- top_p=DEFAULT_TOP_P,
78
- top_k=DEFAULT_TOP_K,
79
- stop_sequences=DEFAULT_STOP_SEQUENCES,
80
- )
81
-
82
- # Update conversation history
83
- history.append({'role': 'user', 'content': message.content})
84
- history.append(assistant_reply)
85
- user_histories[user_id] = history
86
-
87
- # Send the assistant's reply
88
- await message.channel.send(assistant_reply['content'])
89
- except Exception as e:
90
- await message.channel.send(f"An error occurred: {str(e)}")
91
-
92
- # Periodically ping Hugging Face Space to prevent it from sleeping
93
  @tasks.loop(minutes=20)
94
  async def keep_gradio_awake():
95
  print("Sending keep-alive ping...")
96
  if HUGGING_FACE_SPACE_URL:
97
- try:
98
- import aiohttp
99
- async with aiohttp.ClientSession() as session:
100
- async with session.get(HUGGING_FACE_SPACE_URL) as response:
101
- pass # We don't need to do anything with the response
102
- print(f"Pinged {HUGGING_FACE_SPACE_URL} to keep it awake.")
103
- except Exception as e:
104
- print(f"Failed to ping Hugging Face Space: {e}")
105
 
106
- # Run the Discord bot
107
- async def run_discord_bot():
108
- await bot.start(DISCORD_TOKEN)
 
 
 
1
  import discord
2
  import os
3
  import asyncio
4
  from discord.ext import commands, tasks
5
  from dotenv import load_dotenv
6
+ from ai_model import query_ai_model # Import AI model query function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  # Load environment variables
9
  load_dotenv()
10
 
11
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN")
 
 
 
12
  ALLOWED_CHANNELS = os.environ.get("ALLOWED_CHANNELS", "").split(",")
13
  HUGGING_FACE_SPACE_URL = os.environ.get("HUGGING_FACE_SPACE_URL")
14
 
15
  # Configure Discord bot
16
  intents = discord.Intents.default()
17
+ intents.message_content = True
18
  bot = commands.Bot(command_prefix="!", intents=intents)
19
 
 
 
 
20
  # On bot ready
21
  @bot.event
22
  async def on_ready():
23
  print(f"{bot.user} has connected to Discord!")
24
+ keep_gradio_awake.start()
 
 
 
 
 
 
 
25
 
26
+ # Handle commands
27
+ @bot.command()
28
+ async def ask(ctx, *, question):
29
+ if str(ctx.channel.id) not in ALLOWED_CHANNELS:
30
+ await ctx.send("This channel is not allowed for bot interactions.")
31
  return
32
+
33
+ async with ctx.typing():
34
+ response = await query_ai_model(question)
35
+ chunks = [response[i:i+2000] for i in range(0, len(response), 2000)]
36
+ for chunk in chunks:
37
+ await ctx.send(chunk)
38
+
39
+ # Periodically ping Hugging Face Space to prevent sleep
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  @tasks.loop(minutes=20)
41
  async def keep_gradio_awake():
42
  print("Sending keep-alive ping...")
43
  if HUGGING_FACE_SPACE_URL:
44
+ await bot.http.get(HUGGING_FACE_SPACE_URL)
 
 
 
 
 
 
 
45
 
46
+ # Run Discord bot
47
+ def run_discord_bot():
48
+ asyncio.run(bot.start(DISCORD_TOKEN))