-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhammy_bot.py
393 lines (288 loc) · 13 KB
/
hammy_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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env python
#############################
# Import Libraries
import os
import json
import requests
import discord
import time
import xml.etree.ElementTree as et
from urllib import request, error
from datetime import datetime, date, time, timedelta
from geopy.geocoders import Nominatim
from table2ascii import table2ascii as t2a, PresetStyle, Alignment
#############################
# import config json file
with open("config.json", "r") as read_file:
config = json.load(read_file)
#############################
#############################
# Create Discord Bot
TOKEN = config['discord_bot_token']
bot = discord.Bot(debug_guilds=[config['discord_server_id']])
#############################
# Define Variables
# DO NOT CHANGE BELOW
linefeed = "\r\n"
degree_sign= u'\N{DEGREE SIGN}'
aprsfi_api_base_url = "https://api.aprs.fi/api/get"
radioid_base_url = "https://database.radioid.net/api"
radioid_dmrid_url = radioid_base_url + "/dmr/user"
radioid_nxdnid_url = radioid_base_url + "/nxdn/user"
geolocator = Nominatim(user_agent="aprstweet")
debug = False
#############################
# Define Functions
def get_api_data(url,data_type):
if data_type == 'json':
# get JSON data from api's with just a URL
return requests.get(url=url).json()
if data_type =='xml':
# get XML data from api's with just a URL
return et.parse(request.urlopen(url))
def get_api_data_payload(url,payload,data_type):
# get JSON data from api's
if data_type == 'json':
try:
responses = requests.get(url=url,params=payload).json()
except ValueError as e:
return 0
return responses
def get_location(lat,lng):
# Reverse geocode with openstreetmaps for location
osm_address = geolocator.reverse(lat.strip()+","+lng.strip())
return osm_address.address
def get_grid(dec_lat, dec_lon):
## Function developed by Walter Underwood, K6WRU https://ham.stackexchange.com/questions/221/how-can-one-convert-from-lat-long-to-grid-square
# Returns the Grid Square for the packet location
upper = 'ABCDEFGHIJKLMNOPQRSTUVWX'
lower = 'abcdefghijklmnopqrstuvwx'
if not (-180<=dec_lon<180):
sys.stderr.write('longitude must be -180<=lon<180, given %f\n'%dec_lon)
sys.exit(32)
if not (-90<=dec_lat<90):
sys.stderr.write('latitude must be -90<=lat<90, given %f\n'%dec_lat)
sys.exit(33) # can't handle north pole, sorry, [A-R]
adj_lat = dec_lat + 90.0
adj_lon = dec_lon + 180.0
grid_lat_sq = upper[int(adj_lat/10)]
grid_lon_sq = upper[int(adj_lon/20)]
grid_lat_field = str(int(adj_lat%10))
grid_lon_field = str(int((adj_lon/2)%10))
adj_lat_remainder = (adj_lat - int(adj_lat)) * 60
adj_lon_remainder = ((adj_lon) - int(adj_lon/2)*2) * 60
grid_lat_subsq = lower[int(adj_lat_remainder/2.5)]
grid_lon_subsq = lower[int(adj_lon_remainder/5)]
return grid_lon_sq + grid_lat_sq + grid_lon_field + grid_lat_field + grid_lon_subsq + grid_lat_subsq
def get_aprs_position(callsign):
status = ''
fixed_station = False
position_payload = {
'name': callsign,
'what': 'loc',
'apikey': config['aprsfikey'],
'format': 'json'
}
data = get_api_data_payload(aprsfi_api_base_url,position_payload,'json')
if data["found"] == 0:
status = ('No data found for callsign %s' % callsign.upper())
else:
station = data["entries"][0]["name"]
lat = str(data["entries"][0]["lat"])
lng = str(data["entries"][0]["lng"])
lasttime = data["entries"][0]["lasttime"]
if "speed" in data["entries"][0]:
speedkph = float(data["entries"][0]["speed"])
else:
fixed_station = True
#Create Status Message
status = station + ": "+ get_location(lat,lng)
if not fixed_station:
status = status + " | Speed: "+ str(round(speedkph/1.609344,1)) + " mph"
status = status + " | Grid: " + get_grid(float(lat),float(lng))
status = status + " | " + datetime.fromtimestamp(int(lasttime)).strftime('%H:%M:%S') + \
" | https://aprs.fi/" + station
return status
def append_data(record_name,fielddata):
dataset = []
dataset.append(record_name)
dataset.append(fielddata)
return dataset
def lookup_calldata(callsign):
callsigndata = ""
calldata = []
source = ''
radioid_payload = {
"callsign": callsign
}
# Let's get callbook data!
# First, let's check Callook.info for the callsign data
callook_url = "https://callook.info/" + callsign + "/json"
callsign_data = get_api_data(callook_url,'json')
if callsign_data["status"] == 'VALID':
calldata.append(append_data("Callsign:",callsign_data['current']['callsign']))
if callsign_data['previous']['callsign'] != '':
calldata.append(append_data("Previous:",callsign_data['previous']['callsign']))
if callsign_data['type'] == 'PERSON':
calldata.append(append_data("Class:",callsign_data['current']['operClass'].title()))
if callsign_data['type'] == 'CLUB':
calldata.append(append_data("Trustee:",callsign_data['trustee']['name'].title() + ", "+ callsign_data['trustee']['callsign']))
calldata.append(append_data("Name:",callsign_data['name'].title()))
calldata.append(append_data("Address:",callsign_data['address']['line1'].title()))
calldata.append(append_data("",callsign_data['address']['line2'].title()))
calldata.append(append_data("Grid Square:",callsign_data['location']['gridsquare']))
calldata.append(append_data("Grant Date:",callsign_data['otherInfo']['grantDate']))
calldata.append(append_data("Expires:",callsign_data['otherInfo']['expiryDate']))
source = 'Callook.info'
# if the status came back invalid, so no data was found, let's try HamQTH.com for the data.
# This will include International callsign searches.
else:
prefix = '{https://www.hamqth.com}'
callsign_result = ''
name = ''
address = ''
city = ''
state = ''
zip = ''
country = ''
grid = ''
hamqth_sessionid = ''
hamqth_getsession_url = "https://www.hamqth.com/xml.php?u=" + config['hamqth_username'] + "&p=" + config['hamqth_password']
session_data = get_api_data(hamqth_getsession_url,'xml')
root = session_data.getroot()
for item in root.findall(prefix + 'session'):
for child in item:
if child.tag == prefix + 'session_id':
hamqth_sessionid = child.text
if hamqth_sessionid != '':
hamqth_lookup_url = 'https://www.hamqth.com/xml.php?id='+ hamqth_sessionid + '&callsign=' + callsign + '&prg=Hammy_Discord_Bot'
hamqth_data = get_api_data(hamqth_lookup_url,'xml')
root = hamqth_data.getroot()
# for item in root.findall(prefix + 'search'):
# for child in item:
# print(child.tag)
# print(child.text)
for item in root.findall(prefix + 'search'):
for child in item:
if child.tag == prefix + 'callsign':
callsign_result = child.text.upper()
elif child.tag == prefix + 'adr_name':
name = child.text.title()
elif child.tag == prefix + 'adr_street1':
address = child.text.title()
elif child.tag == prefix + 'adr_city':
city = child.text.title()
elif child.tag == prefix + 'us_state':
state = child.text.upper()
elif child.tag == prefix + 'adr_zip':
zip = child.text
elif child.tag == prefix + 'country':
country = child.text
elif child.tag == prefix + 'grid':
grid = child.text
calldata.append(append_data("Callsign:",callsign_result))
calldata.append(append_data("Name:",name))
calldata.append(append_data("Address:",address))
calldata.append(append_data("",str(city) + ', ' + str(state) + ' ' + str(zip)))
calldata.append(append_data("",country))
calldata.append(append_data("Grid Square:",grid))
source = 'HamQTH.com'
if len(calldata) <=0:
callsigndata = "No Callsign Data found." + linefeed
else:
for x in range(len(calldata)):
callsigndata = callsigndata + calldata[x][0] + " " + calldata[x][1] + linefeed
# Now let's get DMR ID Data
dmr_id_data = get_api_data_payload(radioid_dmrid_url,radioid_payload,'json')
if len(dmr_id_data) > 0:
dmr_count = int(dmr_id_data['count'])
callsigndata = callsigndata + "DMR ID(s): "
for i in range(dmr_count):
if i > 0:
callsigndata = callsigndata + ", " + str(dmr_id_data['results'][i]['id'])
else:
callsigndata = callsigndata + str(dmr_id_data['results'][i]['id'])
callsigndata = callsigndata + linefeed
# Now Let's Get NXDN ID Data
nxdn_id_data = get_api_data_payload(radioid_nxdnid_url,radioid_payload,'json')
if len(nxdn_id_data) > 0:
nxdn_count = int(nxdn_id_data['count'])
callsigndata = callsigndata + "NXDN ID(s): "
for i in range(nxdn_count):
if i > 0:
callsigndata = callsigndata + ", " + str(nxdn_id_data['results'][i]['id'])
else:
callsigndata = callsigndata + str(nxdn_id_data['results'][i]['id'])
callsigndata = callsigndata + linefeed
callsigndata = callsigndata + "Source: " + source + ", RadioID.net" + linefeed
# Return whatever data we have found.
return callsigndata
#############################
# Define Discord Bot Functions
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.command(description="Callsign to search for.")
async def callsign(ctx, callsign):
await ctx.respond("This will take a moment to compile the data.", ephemeral=True)
embed = discord.Embed(title = "Callbook Data for " + callsign.upper(),
description=lookup_calldata(callsign.lower()),
)
await ctx.respond(embed = embed, ephemeral=True)
@bot.command(description="DMR ID to search for.")
async def dmr(ctx, dmrid):
await ctx.respond("This will take a moment to compile the data.", ephemeral=True)
radioid_payload = {
"id": dmrid
}
dmr_id_data = get_api_data_payload(radioid_dmrid_url,radioid_payload,'json')
if int(dmr_id_data['count']) > 0 :
embed = discord.Embed(title = "Callbook Data for " + dmr_id_data['results'][0]['callsign'].upper(),
description=lookup_calldata(dmr_id_data['results'][0]['callsign']),
)
else:
embed = discord.Embed(title = "No DMR ID's Found",
description="No ID's Found"
)
await ctx.respond(embed = embed, ephemeral=True)
@bot.command(description="NXDN ID to search for.")
async def nxdn(ctx, nxdnid):
await ctx.respond("This will take a moment to compile the data.", ephemeral=True)
radioid_payload = {
"id": nxdnid
}
nxdn_id_data = get_api_data_payload(radioid_nxdnid_url,radioid_payload,'json')
if int(dmr_id_data['count']) > 0 :
embed = discord.Embed(title = "Callbook Data for " + nxdn_id_data['results'][0]['callsign'].upper(),
description=lookup_calldata(nxdn_id_data['results'][0]['callsign']),
)
else:
embed = discord.Embed(title = "No NXDN ID's Found",
description="No ID's Found"
)
await ctx.respond(embed = embed, ephemeral=True)
@bot.command(description="APRS Station to search for.")
async def aprs(ctx, callsign):
await ctx.respond("This will take a moment to compile the data.", ephemeral=True)
embed = discord.Embed(title = "Last APRS Position",
description=get_aprs_position(callsign),
)
await ctx.respond(embed = embed, ephemeral=True)
@bot.command(description="Help Text")
async def hammy(ctx):
cmd_list = """
/callsign <callsign> - Returns callbook data for the callsign queried, including DMR ID and NXDNID, in a DM. ex: /callsign W1AW.
/dmr <dmrid> - Returns callbook data for the DMR ID queried, including DMR ID and NXDNID, in a DM. ex: /dmr 1234567
/nxdn <nxdnid> - Returns callbook data for the NXDN ID queried, including DMR ID and NXDNID, in a DM. ex: /nxdn 1234567
/aprs <callsign+ssid> - Returns last postion beaconed for the station queried. Note that SSID is optional, but it will not do a wildcard or fuzzy search. ex: /aprs W1AW or /aprs W1AW-9
/hammy - This help text
More information about me can be found at https://github.com/n8acl/hammy-discord-bot
"""
embed = discord.Embed(title = "Hammy Commands",
description=cmd_list
)
await ctx.respond(embed = embed, ephemeral=True)
#############################
# Main Program
# Start Bot
bot.run(TOKEN)