-
Notifications
You must be signed in to change notification settings - Fork 0
/
callsign.py
202 lines (158 loc) · 6.94 KB
/
callsign.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
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
import os, sys, traceback, json
import discord, pymysql.cursors
from dotenv import load_dotenv
load_dotenv()
client = discord.Client()
TOKEN = os.getenv('TOKEN')
NAME = os.getenv('NAME')
conn = pymysql.connect( host = os.getenv('HOST'),
user = os.getenv('DBUSER'),
password = os.getenv('PASSWORD'),
db = os.getenv('DATABASE'),
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor)
def check_if_bot_mentioned(mentions):
if len(mentions) == 0:
return False
else:
for member in mentions:
if NAME in str(member): return True
return False
def has_other_mention(mentions):
if len(mentions) == 0:
return False
else:
for member in mentions:
if NAME not in str(member): return str(member)
return False
def help_response():
return """
**CallSign Bot Help**
__Simple Commands__
- Help (you know this one already!): shows list
ex: `@Callsign help`
- Add {username_on_game_youre_adding} : {game_name}: Adds callsign to game.
Note: This will update name also if game is already in list.
ex: `@CallSign add [UN1T]Example : Squad`
- Remove {game}: Removes Callsigns for game.
ex: `@Callsign remove Ground Branch`
__Lookup Callsigns for Games__
ex: `@Callsign @USER_OF_INTEREST`
- will return list of all callsigns (usernames) in games they have registered.
"""
def get_callsign(msg):
return msg.split(' :', 1)[0]
def user_in_db(user):
user_name = str(user)
with conn.cursor() as cursor:
sql = f"SELECT `id` FROM `callsigns` WHERE `user` = %s"
cursor.execute(sql, (user_name,))
users = cursor.fetchall()
return any(users)
def create_user_in_db(user):
user_name = str(user)
with conn.cursor() as cursor:
sql = f"INSERT INTO `callsigns` (`user`) VALUES (%s) "
cursor.execute(sql, (user_name,))
return conn.commit()
def get_user_callsigns(user):
user_name = str(user)
with conn.cursor() as cursor:
sql = f"SELECT `data` FROM `callsigns` WHERE `user` = %s"
cursor.execute(sql, (user_name,))
results = cursor.fetchone()
return results['data']
def update_callsigns_for_user(user, callsign_list):
user_name = str(user)
data = json.dumps(callsign_list)
with conn.cursor() as cursor:
sql = f"UPDATE `callsigns` SET `data` = %s WHERE `user` = %s"
cursor.execute(sql, (data, user_name))
return conn.commit()
# ====================================================================== #
@client.event
async def on_ready():
print("Callsign is ready to go")
await client.change_presence(game=discord.Game(name="Watching Comms"))
@client.event
async def on_message(message):
try:
# ignore messages from the Bot itself
if message.author == client.user:
return
bot_was_mentioned = check_if_bot_mentioned(message.mentions)
if bot_was_mentioned:
message_content = message.content.lower().strip()
print(message_content)
if " help" in message_content:
await client.send_message(message.channel, help_response())
return
elif " add" in message_content:
user = message.author
callsign = get_callsign( message.content.split(' add ', 1)[1].strip() )
game = message.content.split(' : ', 1)[1].strip()
if user_in_db(user) == False:
create_user_in_db(user)
user_callsigns = get_user_callsigns(user)
if user_callsigns == None:
# Setting a Fresh record for the User
updated_callsigns = {}
updated_callsigns[game] = callsign
else:
# Update the Records for the User
updated_callsigns = json.loads(user_callsigns)
updated_callsigns[game] = callsign
update_callsigns_for_user(user, updated_callsigns)
await client.send_message(message.channel, f"Your Callsign for `{game}` is now `{callsign}`!")
return
elif " remove" in message_content:
user = message.author
game = message.content.split('remove ', 1)[1].strip()
if user_in_db(user) == False:
await client.send_message(message.channel, "You cant remove any Callsigns - You havent even added any!")
return
user_callsigns = get_user_callsigns(user)
if user_callsigns == None:
await client.send_message(message.channel, "You cant remove any Callsigns - You havent even added any!")
return
else:
# Update the Records for the User
updated_callsigns = json.loads(user_callsigns)
if game in updated_callsigns:
del updated_callsigns[game]
else:
await client.send_message(message.channel, f"You dont have a callsign for {game}!")
return
update_callsigns_for_user(user, updated_callsigns)
await client.send_message(message.channel, f"Your Callsign for `{game}` has been removed!")
return
elif has_other_mention(message.mentions) != False:
# Lookup Users CallSigns
user = has_other_mention(message.mentions)
if user_in_db(user) == False:
await client.send_message(message.channel, f"{user} is not in CallSign System Yet.")
return
user_callsigns = get_user_callsigns(user)
if user_callsigns == None:
await client.send_message(message.channel, f"{user} has no CallSigns")
return
else:
callsigns = json.loads(user_callsigns)
if not callsigns:
await client.send_message(message.channel, f"{user} has no CallSigns")
return
else:
response = f"Callsigns for **{user.split('#',1)[0]}**\n\n"
for key in callsigns:
response += f"**{key}** : _{callsigns[key]}_\n"
await client.send_message(message.channel, response)
return
exit()
else:
await client.send_message(message.channel, "Uhh...what? Try @CallSign help.")
return
except Exception:
print(traceback.format_exc())
await client.send_message(message.channel, "Uhh...what? Try @CallSign help.")
return
client.run(TOKEN)