Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscord_bot.py
More file actions
Latest commit
206 lines (183 loc) · 6.64 KB
/
Copy pathdiscord_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
importjson
importos
importaiohttp
importasyncio
frompathlibimportPath
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"
asyncdefsave_token(token):
"""Save Discord token to file"""
try:
data= {"token": token}
withopen(TOKEN_FILE, "w") asf:
json.dump(data, f)
returnTrue
exceptExceptionase:
returnFalse
asyncdefget_token():
"""Retrieve token from file"""
try:
ifos.path.exists(TOKEN_FILE):
withopen(TOKEN_FILE, "r") asf:
data=json.load(f)
returndata.get("token")
returnNone
exceptException:
returnNone
asyncdefvalidate_token(token):
"""Validate Discord token by making a test API call"""
headers= {"Authorization": f"Bot {token}"iftoken.startswith("Bot ") elsetoken}
try:
asyncwithaiohttp.ClientSession() assession:
asyncwithsession.get(f"{API_BASE}/users/@me", headers=headers) asresp:
ifresp.status==200:
returnTrue
returnFalse
exceptException:
returnFalse
asyncdeffetch_messages(token, channel_id, limit=50):
"""Fetch messages from a channel"""
headers= {"Authorization": f"Bot {token}"iftoken.startswith("Bot ") elsetoken}
try:
asyncwithaiohttp.ClientSession() assession:
asyncwithsession.get(f"{API_BASE}/channels/{channel_id}/messages?limit={limit}", headers=headers) asresp:
ifresp.status==200:
messages=awaitresp.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
}
formsginmessages
]
returnsimplified_messages
returnNone
exceptExceptionase:
returnNone
asyncdefsend_message(token, channel_id, content):
"""Send a message to a channel"""
headers= {
"Authorization": f"Bot {token}"iftoken.startswith("Bot ") elsetoken,
"Content-Type": "application/json"
}
payload= {"content": content}
try:
asyncwithaiohttp.ClientSession() assession:
asyncwithsession.post(f"{API_BASE}/channels/{channel_id}/messages",
headers=headers,
json=payload) asresp:
ifresp.statusin (200, 201):
returnawaitresp.json()
returnNone
exceptExceptionase:
returnNone
asyncdeffunction(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
iftoken:
awaitsave_token(token)
else:
# Try to load from file
token=awaitget_token()
ifnottoken:
returnjson.dumps({
"success": False,
"error": "No token provided or saved"
})
# Validate token
ifaction=="validate":
is_valid=awaitvalidate_token(token)
returnjson.dumps({
"success": True,
"valid": is_valid
})
# Fetch messages
ifaction=="fetch":
ifnotchannel_id:
returnjson.dumps({
"success": False,
"error": "Channel ID is required"
})
messages=awaitfetch_messages(token, channel_id, message_limit)
ifmessagesisNone:
returnjson.dumps({
"success": False,
"error": "Failed to fetch messages"
})
returnjson.dumps({
"success": True,
"message": messages
})
# Send message
ifaction=="send":
ifnotchannel_id:
returnjson.dumps({
"success": False,
"error": "Channel ID is required"
})
ifnotcontent:
returnjson.dumps({
"success": False,
"error": "Message content is required"
})
result=awaitsend_message(token, channel_id, content)
ifresultisNone:
returnjson.dumps({
"success": False,
"error": "Failed to send message"
})
returnjson.dumps({
"success": True,
"message": "Message sent successfully",
"data": result
})
returnjson.dumps({
"success": False,
"error": "Invalid action"
})
exceptExceptionase:
returnjson.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"]
}
}