-
Notifications
You must be signed in to change notification settings - Fork 0
/
CharacterAI Discord bot.py
58 lines (48 loc) · 1.87 KB
/
CharacterAI Discord bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import asyncio
import discord
from characterai import aiocai
# Replace these with your actual values
char_id = 'Input Your Characterai Character ID'
CHATOKEN = 'Input Your Characterai Login Token'
TOKEN = "Input Your Discord Bot Token"
intents = discord.Intents.default()
intents.message_content = True
class MyBot(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.chat = None
self.char = char_id
self.client = aiocai.Client(CHATOKEN)
self.chat_history = []
async def on_ready(self):
print(f'Logged in as {self.user}')
me = await self.client.get_me()
async with await self.client.connect() as chat:
self.chat = chat
new, answer = await self.chat.new_chat(self.char, me.id)
self.chat_id = new.chat_id
print(f'{answer.name}: {answer.text}')
async def on_message(self, message):
if message.author == self.user:
return
if message.content.lower() == "nl1027":
await message.channel.send("Shutting down...")
await self.save_chat_history()
await self.close()
return
async with await self.client.connect() as chat:
chat_response = await chat.send_message(self.char, self.chat_id, message.content)
self.chat_history.append(
f"{message.author.name}: {message.content}\n{self.user.name}: {chat_response.text}\n"
)
await self.save_chat_history()
await message.channel.send(chat_response.text)
async def save_chat_history(self):
with open("chat_history.txt", "a") as f:
for entry in self.chat_history:
f.write(entry)
self.chat_history.clear()
async def main():
client = MyBot(intents=intents)
await client.start(TOKEN)
asyncio.run(main())