-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscord_bot.py
More file actions
206 lines (183 loc) · 6.64 KB
/
discord_bot.py
File metadata and controls
206 lines (183 loc) · 6.64 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import json
import os
import aiohttp
import asyncio
from pathlib import Path
public_description = "Manage Discord token and handle message operations (fetch and send)"
# Constants
TOKEN_FILE = os.path.join(os.path.expanduser("~"), ".discord_token.json")
API_BASE = "https://discord.com/api/v10"
async def save_token(token):
"""Save Discord token to file"""
try:
data = {"token": token}
with open(TOKEN_FILE, "w") as f:
json.dump(data, f)
return True
except Exception as e:
return False
async def get_token():
"""Retrieve token from file"""
try:
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, "r") as f:
data = json.load(f)
return data.get("token")
return None
except Exception:
return None
async def validate_token(token):
"""Validate Discord token by making a test API call"""
headers = {"Authorization": f"Bot {token}" if token.startswith("Bot ") else token}
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{API_BASE}/users/@me", headers=headers) as resp:
if resp.status == 200:
return True
return False
except Exception:
return False
async def fetch_messages(token, channel_id, limit=50):
"""Fetch messages from a channel"""
headers = {"Authorization": f"Bot {token}" if token.startswith("Bot ") else token}
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"{API_BASE}/channels/{channel_id}/messages?limit={limit}", headers=headers) as resp:
if resp.status == 200:
messages = await resp.json()
# Format messages to simpler format with just name and content
simplified_messages = [
{
"name": msg["author"].get("global_name", msg["author"]["username"]),
"content": msg["content"],
"timestamp": msg["timestamp"],
"has_attachments": len(msg.get("attachments", [])) > 0
}
for msg in messages
]
return simplified_messages
return None
except Exception as e:
return None
async def send_message(token, channel_id, content):
"""Send a message to a channel"""
headers = {
"Authorization": f"Bot {token}" if token.startswith("Bot ") else token,
"Content-Type": "application/json"
}
payload = {"content": content}
try:
async with aiohttp.ClientSession() as session:
async with session.post(f"{API_BASE}/channels/{channel_id}/messages",
headers=headers,
json=payload) as resp:
if resp.status in (200, 201):
return await resp.json()
return None
except Exception as e:
return None
async def function(args):
try:
action = args.get("action")
token = args.get("token")
channel_id = args.get("channel_id")
content = args.get("content")
message_limit = int(args.get("limit", 50))
# Automatically save token if provided
if token:
await save_token(token)
else:
# Try to load from file
token = await get_token()
if not token:
return json.dumps({
"success": False,
"error": "No token provided or saved"
})
# Validate token
if action == "validate":
is_valid = await validate_token(token)
return json.dumps({
"success": True,
"valid": is_valid
})
# Fetch messages
if action == "fetch":
if not channel_id:
return json.dumps({
"success": False,
"error": "Channel ID is required"
})
messages = await fetch_messages(token, channel_id, message_limit)
if messages is None:
return json.dumps({
"success": False,
"error": "Failed to fetch messages"
})
return json.dumps({
"success": True,
"message": messages
})
# Send message
if action == "send":
if not channel_id:
return json.dumps({
"success": False,
"error": "Channel ID is required"
})
if not content:
return json.dumps({
"success": False,
"error": "Message content is required"
})
result = await send_message(token, channel_id, content)
if result is None:
return json.dumps({
"success": False,
"error": "Failed to send message"
})
return json.dumps({
"success": True,
"message": "Message sent successfully",
"data": result
})
return json.dumps({
"success": False,
"error": "Invalid action"
})
except Exception as e:
return json.dumps({
"success": False,
"error": str(e)
})
object = {
"name": "discord_bot",
"description": "Manage Discord token and handle message operations (fetch and send)",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["validate", "fetch", "send"],
"description": "Action to perform with Discord"
},
"token": {
"type": "string",
"description": "Discord token (optional if previously saved)"
},
"channel_id": {
"type": "string",
"description": "Discord channel ID for message operations"
},
"content": {
"type": "string",
"description": "Content for sending messages"
},
"limit": {
"type": "integer",
"description": "Maximum number of messages to fetch (default: 50)"
}
},
"required": ["action"]
}
}