This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
2160 lines (1875 loc) · 84.8 KB
/
main.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# /bin/python3
from __future__ import annotations
import asyncio
import functools
import json
import math
import os
import random
import re
import time
from datetime import datetime
from io import BytesIO
from multiprocessing import Pool
from typing import Any
from typing import Iterable
from typing import Union
from urllib.parse import quote
import aiohttp
import discord
import overpy
import requests
from discord import AllowedMentions
from discord import Client
from discord import Embed
from discord import File
from discord import Guild
from discord import Intents
from discord import Member
from discord import Message
from discord_slash import SlashCommand
from discord_slash import SlashContext
from discord_slash.context import ComponentContext
from discord_slash.model import ButtonStyle
from discord_slash.model import SlashMessage
from discord_slash.utils import manage_components
from discord_slash.utils.manage_commands import create_choice
from discord_slash.utils.manage_commands import create_option
from dotenv import load_dotenv
from PIL import Image
from PIL import ImageDraw # For drawing elements
## SETUP ##
# Regex
SS = r"(?<!\/|\w)" # Safe Start
SE = r"(?!\/|\w)" # Safe End
DECIMAL = r"[+-]?(?:[0-9]*\.)?[0-9]+"
POS_INT = r"[0-9]+"
# Discord message link
DISC_MSG_LINK_REGEX = r"(?:https?:)?\/\/(?:\w+\.)?discord\.com\/channels\/([0-9]+)\/([0-9]+)\/([0-9]+)\/?"
### Inline linking ###
ELM_INLINE_REGEX = rf"{SS}(node|way|relation)(s? |\/)({POS_INT}(?:(?:, | and | or | )(?:{POS_INT}))*){SE}"
CHANGESET_INLINE_REGEX = rf"{SS}(changeset)(s? |\/)({POS_INT}(?:(?:, | and | or | )(?:{POS_INT}))*){SE}"
NOTE_INLINE_REGEX = rf"{SS}(note)(s? |\/)({POS_INT}(?:(?:, | and | or | )(?:{POS_INT}))*){SE}"
USER_INLINE_REGEX = rf"{SS}user\/[\w\-_]+{SE}"
# FIXME: For some reason this allows stuff after the end of the map fragment.
MAP_FRAGMENT_INLINE_REGEX = rf"{SS}#map={POS_INT}\/{DECIMAL}\/{DECIMAL}{SE}"
MAP_FRAGEMT_CAPTURING_REGEX = rf"#map=({POS_INT})\/({DECIMAL})\/({DECIMAL})"
# This global set contains filename similar to /fate. If on_message fails, it will remove cached files on next run.
cached_files: set = set()
# Set of unix timestamps.
recent_fates: set = set()
command_history: dict = dict() # Global per-user dictionary of sets to keep track of rate-limiting per-user.
### Rendering ###
max_zoom = 19 # Maximum zoom level without notes.
max_note_zoom = 17 # Maximum zoom, when notes are present on map.
tile_w, tile_h = 256, 256 # Tile size used for renderer
tiles_x, tiles_y = 5, 5 # Dimensions of output map fragment
tile_margin_y, tile_margin_x = 0.1, 0.1 # How much free space is left at edges
# Used in render_elms_on_cluster. List of colours to be cycled.
element_colors = ["#000", "#700", "#f00", "#070", "#0f0", "#f60"]
### Rate-limiting ###
# These 2 are used in check_rate_limit
time_period = 30
max_calls = 10
# Following 4 are used by on_message
max_elements = 10
element_count_exp = round(math.log(max_calls, max_elements), 2) # 1.17
rate_extra_exp = 1.8
rendering_rate_exp = 0.8
HEADERS = {
"User-Agent": "OSM Discord Bot <https://github.com/GoodClover/OSM-Discord-bot>",
"Accept": "image/png",
"Accept-Charset": "utf-8",
"Accept-Encoding": "none",
"Accept-Language": "en-GB,en",
"Connection": "keep-alive",
}
def load_config() -> None:
global config, guild_ids
# LINK - config.json
with open("config.json", "r", encoding="utf8") as file:
config = json.loads(file.read())
guild_ids = [int(x) for x in config["server_settings"].keys()]
def save_config() -> None:
global config
# LINK - config.json
with open("config.json", "w", encoding="utf8") as file:
file.write(json.dumps(config, indent=4))
config: dict[str, Any] = {}
guild_ids: list[int] = []
load_config()
DISC_MSG_LINK_REGEX = re.compile(DISC_MSG_LINK_REGEX, re.IGNORECASE)
ELM_INLINE_REGEX = re.compile(ELM_INLINE_REGEX, re.IGNORECASE)
CHANGESET_INLINE_REGEX = re.compile(CHANGESET_INLINE_REGEX, re.IGNORECASE)
NOTE_INLINE_REGEX = re.compile(NOTE_INLINE_REGEX, re.IGNORECASE)
USER_INLINE_REGEX = re.compile(USER_INLINE_REGEX, re.IGNORECASE)
MAP_FRAGMENT_INLINE_REGEX = re.compile(MAP_FRAGMENT_INLINE_REGEX, re.IGNORECASE)
INTEGER_REGEX = re.compile(POS_INT)
overpass_api = overpy.Overpass(url=config["overpass_url"])
res = requests.get(config["symbols"]["note_solved"], headers=HEADERS)
closed_note_icon = Image.open(BytesIO(res.content))
res = requests.get(config["symbols"]["note_open"], headers=HEADERS)
open_note_icon = Image.open(BytesIO(res.content))
open_note_icon_size = open_note_icon.size
closed_note_icon_size = closed_note_icon.size
INSPECT_EMOJI = "🔎" # :mag_right:
IMAGE_EMOJI = "🖼️" # :frame_photo:
EMBEDDED_EMOJI = "🛏️" # :bed:
CANCEL_EMOJI = "❌" # :x:
DELETE_EMOJI = "🗑️" # :wastebasket:
LOADING_EMOJI = config["emoji"]["loading"] # :loading:
LEFT_SYMBOL = "←"
RIGHT_SYMBOL = "→"
CANCEL_SYMBOL = "✘"
with open(config["ohno_file"], "r", encoding="utf8") as file:
ohnos = [entry for entry in file.read().split("\n\n") if entry != ""]
with open(config["josm_tips_file"], "r", encoding="utf8") as file:
josm_tips = [entry for entry in file.read().split("\n\n") if entry != ""]
client = Client(
intents=Intents.all(),
allowed_mentions=AllowedMentions(
# I also use checks elsewhere to prevent @ injection.
everyone=False,
users=True,
roles=False,
replied_user=False,
),
)
slash = SlashCommand(client, sync_commands=True)
## UTILS ##
def is_powerful(member: Member, guild: Guild) -> bool:
return guild.get_role(config["server_settings"][str(guild.id)]["power_role"]) in member.roles
def str_to_date(text: str, suffix: str = "Z") -> datetime:
return datetime.strptime(text, "%Y-%m-%dT%H:%M:%S" + suffix)
def date_to_mention(date: datetime) -> str:
return f"<t:{int(date.timestamp())}>"
def sanitise(text: str) -> str:
"""Make user input safe to just copy."""
text = text.replace("@", "�")
return text
def check_rate_limit(user, extra=0):
# Sorry for no typehints, i don't know what types to have
tnow = round(time.time(), 1)
if user not in command_history:
command_history[user] = set()
# Extra is useful in case when user queries lot of elements in one query.
command_history[user].add(tnow + extra)
command_history[user] = set(filter(lambda x: x > tnow - time_period, command_history[user]))
# print(user, command_history[user])
if len(command_history[user]) > max_calls:
return False
return True
def get_suffixed_tag(
tags: dict[str, str],
key: str,
suffix: str,
) -> tuple[str, str] | tuple[None, None]:
# Looks like two style checkers tend to disagree on argument whitespacing.
suffixed_key = key + suffix
if suffixed_key in tags:
return suffixed_key, tags[suffixed_key]
elif key in tags:
return key, tags[key]
else:
return None, None
# This doesn't work correct.
# def comma_every_three(text: str) -> str:
# return ",".join(re.findall("...", str(text)[::-1]))[::-1]
def msg_to_link(msg: Union[Message, SlashMessage]) -> str:
return f"https://discord.com/channels/{msg.guild.id}/{msg.channel.id}/{msg.id}"
def user_to_mention(user: Member) -> str:
return f"<@{user.id}>"
## CLIENT ##
@client.event # type: ignore
async def on_ready() -> None:
print(f"{client.user} is connected to the following guilds:\n")
for guild in client.guilds:
try:
# Update member count when bot starts up
await update_member_count(guild)
except:
pass
print(f" - {guild.name}: {guild.id}")
# print(" - " + "\n - ".join([f"{guild.name}: {guild.id}" for guild in client.guilds]))
# I got annoyed by people using googlebad so often, so i implemented an easter egg.
# Fate (formerly Google Bad)
@slash.slash(name="fate", description="Mailing lists fall silent… the nodes are uneasy…", guild_ids=guild_ids) # type: ignore
async def fate_command(ctx: SlashContext) -> None:
global recent_fates
time_now = time.time()
recent_fates = set(filter(lambda x: x > time_now - 60, recent_fates)).union({time_now})
if len(recent_fates) > 4 and random.random() > 0.7:
# Alternative output is triggered at 30% chance after 5 /fates are used in 1 minute.
recent_fates = set()
await ctx.send(random.choice(ohnos).replace("…", "Due to overuse of `/fate`,"))
else:
await ctx.send(random.choice(ohnos))
# JOSM Tip
@slash.slash(name="josmtip", description="Get a JOSM tip.", guild_ids=guild_ids) # type: ignore
async def josmtip_command(ctx: SlashContext) -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
await ctx.send(random.choice(josm_tips))
# Quota query
@slash.slash(name="quota", description="Shows your spam limit.", guild_ids=guild_ids) # type: ignore
async def quota_command(ctx: SlashContext) -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
tnow = time.time()
msg = "\n".join(
list(
map(
lambda x: f"Command available in {round(x+time_period-tnow)} sec.",
sorted(command_history[ctx.author_id]),
)
)
)
msg += f"\nYou can still send {max_calls-len(command_history[ctx.author_id])} actions to this bot."
await ctx.send(msg, hidden=True)
### TagInfo ###
@slash.slash(
name="taginfo",
description="Show taginfo for a tag.",
guild_ids=guild_ids,
options=[
create_option(
name="tag",
description="The tag or key.\ne.g. `highway=road` or `building=*`",
option_type=3,
required=True,
)
],
) # type: ignore
async def taginfo_command(ctx: SlashContext, tag: str) -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
split_tag = tag.replace("`", "").split("=", 1)
if len(split_tag) == 2:
if split_tag[1] == "*" or "":
del split_tag[1]
if len(split_tag) == 1:
await ctx.defer()
await ctx.send(embed=taginfo_embed(split_tag[0]))
elif len(split_tag) == 2:
await ctx.defer()
await ctx.send(embed=taginfo_embed(split_tag[0], split_tag[1]))
else:
await ctx.send("Please provide a tag.", hidden=True)
def taginfo_embed(key: str, value: str | None = None) -> Embed:
if value:
data = requests.get(config["taginfo_url"] + f"api/4/tag/stats?key={quote(key)}&value={quote(value)}").json()
data_wiki = requests.get(
config["taginfo_url"] + f"api/4/tag/wiki_pages?key={quote(key)}&value={quote(value)}"
).json()
else:
data = requests.get(config["taginfo_url"] + f"api/4/key/stats?key={quote(key)}").json()
data_wiki = requests.get(config["taginfo_url"] + f"api/4/key/wiki_pages?key={quote(key)}").json()
data_wiki_en_list = [lang for lang in data_wiki["data"] if lang["lang"] == "en"]
data_wiki_en = data_wiki_en_list[0] if data_wiki_en_list else None
#### Embed ####
embed = Embed()
embed.type = "rich"
embed.title = key
if value:
embed.title += "=" + value
if value:
embed.url = config["taginfo_url"] + "tags/" + quote(key) + "=" + quote(value)
else:
embed.url = config["taginfo_url"] + "keys/" + quote(key)
embed.set_footer(
text=config["taginfo_copyright_notice"],
icon_url=config["taginfo_icon_url"],
)
if data_wiki_en and data_wiki_en["image"]["image_url"]:
embed.set_thumbnail(
url=data_wiki_en["image"]["thumb_url_prefix"]
+ str(config["thumb_size"])
+ data_wiki_en["image"]["thumb_url_suffix"]
)
else:
embed.set_thumbnail(url=config["symbols"]["tag" if value else "key"])
# This is the last time taginfo updated:
embed.timestamp = str_to_date(data["data_until"])
# embed.set_author(name="taginfo", url=config["taginfo_url"] + "about")
if data_wiki_en:
embed.description = data_wiki_en["description"]
#### Fields ####
d = data["data"][0]
embed.add_field(
# This gets the emoji. Removes "s" from the end if it is there to do this.
name=config["emoji"][d["type"] if d["type"][-1] != "s" else d["type"][:-1]] + " " + d["type"],
value=(f"{d['count']} - {round(d['count_fraction']*100,2)}%" + (f"\n{d['values']} values" if not value else ""))
if d["count"] > 0
else "*None*",
inline=False,
)
del data["data"][0]
for d in data["data"]:
embed.add_field(
# This gets the emoji. Removes "s" from the end if it is there to do this.
name=config["emoji"][d["type"] if d["type"][-1] != "s" else d["type"][:-1]] + " " + d["type"],
value=(
f"{d['count']} - {round(d['count_fraction']*100,2)}%" + (f"\n{d['values']} values" if not value else "")
)
if d["count"] > 0
else "*None*",
inline=True,
)
return embed
### Elements ###
@slash.slash(
name="elm",
description="Show details about an element.",
guild_ids=guild_ids,
options=[
create_option(
name="elm_type",
description="The element's type",
option_type=3,
required=True,
choices=[
create_choice(name="node", value="node"),
create_choice(name="way", value="way"),
create_choice(name="relation", value="relation"),
],
),
create_option(
name="elm_id",
description="ID of the element",
option_type=4,
required=True,
),
create_option(
name="extras",
description="Comma seperated list of extras from `info`, `tags`, `map` and `members`.",
option_type=3,
required=False,
),
],
) # type: ignore
async def elm_command(ctx: SlashContext, elm_type: str, elm_id: str, extras: str = "") -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
extras_list = [e.strip() for e in extras.lower().split(",")]
for extra in extras_list:
if extra != "" and extra not in ["info", "tags", "members", "map"]:
await ctx.send(
f"Unrecognised extra `{extra}`.\nPlease choose from `info`, `tags` and `members`.", hidden=True
)
return
if elm_type != "relation" and "members" in extras_list:
await ctx.send("Cannot show `members` of non-relation element.", hidden=True)
return
try:
elm = get_elm(elm_type, elm_id)
except ValueError as error_message:
await ctx.send(error_message, hidden=True)
return
files = []
if "map" in extras_list:
await ctx.defer()
render_queue = await elms_to_render(elm_type, elm_id)
check_rate_limit(ctx.author_id, extra=len(render_queue) ** rendering_rate_exp)
bbox = get_render_queue_bounds(render_queue)
zoom, lat, lon = calc_preview_area(bbox)
cluster, filename, errors = await get_image_cluster(lat, lon, zoom)
cached_files.add(filename)
cluster, filename2 = render_elms_on_cluster(cluster, render_queue, (zoom, lat, lon))
cached_files.add(filename2)
embed = elm_embed(elm, extras_list)
file = None
if "map" in extras_list:
print("attachment://" + filename2.split("/")[-1])
embed.set_image(url="attachment://" + filename2.split("/")[-1])
file = File(filename2)
await ctx.send(embed=embed, file=file)
def get_elm(elm_type: str, elm_id: str | int, suffix: str = "") -> dict:
res = requests.get(config["api_url"] + f"api/0.6/{elm_type}/{elm_id}.json" + suffix)
code = res.status_code
if code == 410:
raise ValueError(f"{elm_type.capitalize()} `{elm_id}` has been deleted.")
elif code == 404:
raise ValueError(f"{elm_type.capitalize()} `{elm_id}` has never existed.")
try:
elm = res.json()["elements"][0]
except (json.decoder.JSONDecodeError, IndexError, KeyError):
raise ValueError(f"{elm_type.capitalize()} `{elm_id}` was not found.")
return elm
def elm_embed(elm: dict, extras: Iterable[str] = []) -> Embed:
embed = Embed()
embed.type = "rich"
embed.url = config["site_url"] + elm["type"] + "/" + str(elm["id"])
embed.set_footer(
text=config["copyright_notice"],
icon_url=config["icon_url"],
)
embed.set_thumbnail(url=config["symbols"][elm["type"]])
embed.timestamp = str_to_date(elm["timestamp"])
# embed.set_author(name=elm["user"], url=config["site_url"] + "user/" + elm["user"])
embed.title = elm["type"].capitalize() + ": "
if "tags" in elm:
key, name = get_suffixed_tag(elm["tags"], "name", ":en")
else:
name = None
if name:
embed.title += f"{name} ({elm['id']})"
else:
embed.title += str(elm["id"])
if elm["type"] == "node":
embed.description = f"[{elm['lat']}, {elm['lon']}](<geo:{elm['lat']},{elm['lon']}>)\n"
else:
embed.description = ""
embed.description += (
f"[Edit](<https://www.osm.org/edit?{elm['type']}={elm['id']}>)"
" • "
f"[Level0](<http://level0.osmz.ru/?url={elm['type']}/{elm['id']}>)"
"\n"
f"[OSM History Viewer](<https://pewu.github.io/osm-history/#/{elm['type']}/{elm['id']}>)"
" • "
# Note: https://aleung.github.io/osm-visual-history is basically identical, but has some minor fixes missing.
# I'm using "Visual History" as the name, despite linking to deep history, as it decribes it's function better.
f"[Visual History](<https://osmlab.github.io/osm-deep-history/#/{elm['type']}/{elm['id']}>)"
)
# ? Maybe make it read `colour=` tags for some extra pop?
# if "colour" in elm["tags"]:
# str_to_colour is not needed because PIL supports
# both hex and string coulors just like OSM.
# embed.colour = str_to_colour(elm["tags"]["colour"])
#### Image ####
# * This would create significant stress to the OSM servers, so I don't reccomend it.
# ! This doesn't work due to the OSM servers having some form of token check.
# img_url = (
# "https://render.openstreetmap.org/cgi-bin/export?bbox="
# f"{elm['lon']-0.001},{elm['lat']-0.001},{elm['lon']+0.001},{elm['lat']+0.001}"
# "&scale=1800&format=png"
# )
# embed.set_image(url=img_url)
# Image of element is handled separately.
#### Fields ####
if "info" in extras:
embed.add_field(name="ID", value=elm["id"])
embed.add_field(name="Version", value=f"#{elm['version']}")
embed.add_field(name="Last edited", value=elm["timestamp"])
embed.add_field(
name="Last changeset", value=f"[{elm['changeset']}](<https://www.osm.org/changeset/{elm['changeset']}>)"
)
embed.add_field(name="Last editor", value=f"[{elm['user']}](<https://www.osm.org/user/{quote(elm['user'])}>)")
if elm["type"] == "node":
# Discord doesn't appear to link the geo: URI :( I've left incase it gets supported at some time.
embed.add_field(
name="Position (lat/lon)", value=f"[{elm['lat']}, {elm['lon']}](<geo:{elm['lat']},{elm['lon']}>)"
)
if "tags" in elm:
if "wikidata" in elm["tags"]:
embed.add_field(
name="Wikidata",
value=f"[{elm['tags']['wikidata']}](<https://www.wikidata.org/wiki/{elm['tags']['wikidata']}>)",
)
elm["tags"].pop("wikidata")
if "wikipedia" in elm["tags"]:
# Will automatically redirect to language linked in tag.
embed.add_field(
name="Wikipedia",
value=f"[{elm['tags']['wikipedia']}](<https://wikipedia.org/wiki/{quote(elm['tags']['wikipedia'])}>)",
)
elm["tags"].pop("wikipedia")
# "description", "inscription"
for key in ["note", "FIXME", "fixme"]:
key_languaged, value = get_suffixed_tag(elm["tags"], "note", ":en")
if value:
elm["tags"].pop(key_languaged)
embed.add_field(name=key.capitalize(), value="> " + value, inline=False)
if "tags" in extras:
if "tags" in elm:
embed.add_field(
name="Tags",
value="\n".join([f"`{k}={v}`" for k, v in elm["tags"].items()]),
inline=False,
)
else:
embed.add_field(name="Tags", value="*(no tags)*", inline=False)
if "members" in extras:
if elm["type"] != "relation":
raise ValueError("Cannot show members of non-relation element.")
if "members" in elm:
text = "- " + "\n- ".join(
[
f"{config['emoji'][member['type']]} "
+ (f"`{member['role']}` " if member["role"] != "" else "")
+ f"[{member['ref']}](https://osm.org/{member['type']}/{member['ref']})"
for member in elm["members"]
]
)
if len(text) > 1024:
text = f"Too many members to list.\n[View on OSM.org](https://osm.org/{elm['type']}/{elm['id']})"
embed.add_field(name="Members", value=text, inline=False)
else:
embed.add_field(name="Members", value="*(no members)*", inline=False)
return embed
### Changesets ###
@slash.slash(
name="changeset",
description="Show details about a changeset.",
guild_ids=guild_ids,
options=[
create_option(
name="changeset_id",
description="ID of the changeset",
option_type=4,
required=True,
),
create_option(
name="extras",
description="Comma seperated list of extras from `info`, `tags`, `map`, `discussion`.",
option_type=3,
required=False,
),
],
) # type: ignore
async def changeset_command(ctx: SlashContext, changeset_id: str, extras: str = "") -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
extras_list = [e.strip() for e in extras.lower().split(",")]
for extra in extras_list:
if extra != "" and extra not in ["info", "tags", "map", "discussion"]:
await ctx.send(f"Unrecognised extra `{extra}`.\nPlease choose from `info` and `tags`.", hidden=True)
return
try:
changeset = get_changeset(changeset_id, "discussion" in extras)
except ValueError as error_message:
await ctx.send(error_message, hidden=True)
return
files = []
if "map" in extras_list:
await ctx.defer()
render_queue = changeset["geometry"]
check_rate_limit(ctx.author_id)
bbox = get_render_queue_bounds(render_queue)
zoom, lat, lon = calc_preview_area(bbox)
cluster, filename, errors = await get_image_cluster(lat, lon, zoom)
cached_files.add(filename)
cluster, filename2 = render_elms_on_cluster(cluster, render_queue, (zoom, lat, lon))
cached_files.add(filename2)
embed = changeset_embed(changeset, extras_list)
file = None
if "map" in extras_list:
print("attachment://" + filename2.split("/")[-1])
embed.set_image(url="attachment://" + filename2.split("/")[-1])
file = File(filename2)
await ctx.send(embed=embed, file=file)
def get_changeset(changeset_id: str | int, discussion: bool = False) -> dict:
"""Shorthand for `get_elm("changeset", changeset_id)`"""
try:
discussion_suffix = ""
if discussion:
discussion_suffix = "?include_discussion=true"
changeset = get_elm("changeset", changeset_id, discussion_suffix)
changeset["geometry"] = [
[
(changeset["minlat"], changeset["minlon"]),
(changeset["minlat"], changeset["maxlon"]),
(changeset["maxlat"], changeset["maxlon"]),
(changeset["maxlat"], changeset["minlon"]),
(changeset["minlat"], changeset["minlon"]),
]
]
return changeset
except ValueError as error_message:
raise ValueError(error_message)
def changeset_embed(changeset: dict, extras: Iterable[str] = []) -> Embed:
embed = Embed()
embed.type = "rich"
embed.url = config["site_url"] + "changeset/" + str(changeset["id"])
embed.set_footer(
text=config["copyright_notice"],
icon_url=config["icon_url"],
)
# There doesn't appear to be a changeset icon
# embed.set_thumbnail(url=config["symbols"]["changeset"])
embed.timestamp = str_to_date(changeset["closed_at"])
embed.set_author(name=changeset["user"], url=config["site_url"] + "user/" + quote(changeset["user"]))
embed.title = f"Changeset: {changeset['id']}"
#### Description ####
embed.description = ""
if "tags" in changeset and "comment" in changeset["tags"]:
embed.description += "> " + changeset["tags"]["comment"].strip().replace("\n", "\n> ") + "\n\n"
changeset["tags"].pop("comment")
else:
embed.description += "*(no comment)*\n\n"
#### Image ####
# * This would create significant stress to the OSM servers, so I don't reccomend it.
# ! This doesn't work due to the OSM servers having some form of token check.
# img_url = (
# "https://render.openstreetmap.org/cgi-bin/export?bbox="
# f"{changeset['minlon']},{changeset['minlat']},{changeset['maxlon']},{changeset['maxlat']}"
# "&scale=1800&format=png"
# )
# embed.set_image(url=img_url)
# Easiest way to handle changeset rendering is to just draw bounding box to top tile.
#### Fields ####
if "info" in extras:
embed.add_field(name="Comments", value=changeset["comments_count"])
embed.add_field(name="Changes", value=changeset["changes_count"])
embed.add_field(name="Created", value=date_to_mention(str_to_date(changeset["created_at"])))
embed.add_field(name="Closed", value=date_to_mention(str_to_date(changeset["closed_at"])))
if "tags" in changeset:
if "source" in changeset["tags"]:
embed.add_field(name="Source", value=changeset["tags"]["source"])
changeset["tags"].pop("source")
if "created_by" in changeset["tags"]:
embed.add_field(name="Created by", value=changeset["tags"]["created_by"])
changeset["tags"].pop("created_by")
if "tags" in extras:
if "tags" in changeset:
embed.add_field(
name="Tags",
value="- " + "\n- ".join([f"`{k}={v}`" for k, v in changeset["tags"].items()]),
inline=False,
)
else:
embed.add_field(name="Tags", value="*(no tags)*", inline=False)
# ?include_discussion=true
if "discussion" in extras:
if changeset["comments_count"] > 0:
# Example: *- User opened on 2020-04-14 08:00*
embed.description += (
"\n\n".join(
list(
map(
lambda x: "> "
+ x["text"].strip().replace("\n\n", "\n").replace("\n", "\n> ")
+ f"\n*- {x['user']} on {date_to_mention(str_to_date( x['date']))}*",
changeset["discussion"],
)
)
)
+ "\n\n"
)
else:
embed.description += "*No comments*\n\n"
if len(embed.description) > 1980:
embed.description = embed.description[:1970].strip() + "…\n\n"
embed.description += f"[OSMCha](https://osmcha.org/changesets/{changeset['id']})"
return embed
### Notes ###
# Notes support was added based on changeset
@slash.slash(
name="note",
description="Show details about a note.",
guild_ids=guild_ids,
options=[
create_option(
name="note_id",
description="ID of the note",
option_type=4,
required=True,
),
create_option(
name="extras",
description="Comma seperated list of extras from `info`, `discussion`.",
option_type=3,
required=False,
),
],
) # type: ignore
async def note_command(ctx: SlashContext, note_id: str, extras: str = "") -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
extras_list = [e.strip() for e in extras.lower().split(",")]
for extra in extras_list:
if extra != "" and extra not in ["info", "discussion"]:
await ctx.send(f"Unrecognised extra `{extra}`.\nPlease choose from `info`.", hidden=True)
return
try:
note = get_note(note_id)
except ValueError as error_message:
await ctx.send(error_message, hidden=True)
return
await ctx.defer()
await ctx.send(embed=note_embed(note, extras_list))
def get_note(note_id: str | int) -> dict:
"""Shorthand for get_elm didn't work"""
res = requests.get(config["api_url"] + f"api/0.6/notes/{note_id}.json")
try:
elm = res.json()
except (json.decoder.JSONDecodeError, IndexError, KeyError):
raise ValueError(f"Note `{note_id}` does not exist.")
return elm
def note_embed(note: dict, extras: Iterable[str] = []) -> Embed:
embed = Embed()
embed.type = "rich"
embed.url = config["site_url"] + "note/" + str(note["properties"]["id"])
embed.set_footer(
text=config["copyright_notice"],
icon_url=config["icon_url"],
)
# API returns very different result for notes
if note["properties"]["status"] == "closed":
closed = True
embed.set_thumbnail(url=config["symbols"]["note_solved"])
else:
closed = False
embed.set_thumbnail(url=config["symbols"]["note_open"])
embed.timestamp = str_to_date(note["properties"]["date_created"].replace(" ", "T")[:19] + "Z")
if "user" in note["properties"]["comments"][0]:
creator = note["properties"]["comments"][0]["user"]
embed.set_author(name=creator, url=note["properties"]["comments"][0]["user_url"])
else:
creator = "*Anonymous*"
embed.set_author(name=creator)
embed.title = f"Note: {note['properties']['id']}"
#### Description ####
embed.description = ""
if "comments" in note["properties"] and len(note["properties"]) > 0:
embed.description += "> " + note["properties"]["comments"][0]["text"].strip().replace("\n", "\n> ") + "\n\n"
note["properties"]["comments"].pop(0)
else:
embed.description += "*(no comment)*\n\n"
#### Image ####
# * This would create significant stress to the OSM servers, so I don't reccomend it.
# ! This doesn't work due to the OSM servers having some form of token check.
# embed.set_image(url=img_url)
# Easiest way to handle note rendering is to just draw on map.
#### Fields ####
if "info" in extras:
embed.add_field(name="Comments", value=str(len(note["properties"]["comments"])))
embed.add_field(name="Created", value=date_to_mention(str_to_date(note["properties"]["date_created"])))
if ["closed_at"] in note["properties"]["closed_at"]:
embed.add_field(name="Closed", value=date_to_mention(str_to_date(note["properties"]["closed_at"])))
if "discussion" in extras:
if note["properties"]["comments"]:
# Example: *- User opened on 2020-04-14 08:00*
embed.description += (
"\n\n".join(
list(
map(
lambda x: "> "
+ x["text"].strip().replace("\n\n", "\n").replace("\n", "\n> ")
+ f"\n*- {x['user']} {x['action']} on {date_to_mention(str_to_date(x['date']))}*",
note["properties"]["comments"],
)
)
)
+ "\n\n"
)
else:
embed.description += "*No comments*\n\n"
if creator != "*Anonymous*":
embed.description += f"[Other notes by {creator}.](https://www.openstreetmap.org/user/{creator}/notes)"
return embed
### Users ###
@slash.slash(
name="user",
description="Show details about a user.",
guild_ids=guild_ids,
options=[
create_option(
name="username",
description="Username of the user.",
option_type=3,
required=True,
),
create_option(
name="extras",
description="Comma seperated list of extras from `info`.",
option_type=3,
required=False,
),
],
) # type: ignore
async def user_command(ctx: SlashContext, username: str, extras: str = "") -> None:
if not check_rate_limit(ctx.author_id):
await ctx.send("You have hit the limiter.", hidden=True)
return
extras_list = [e.strip() for e in extras.lower().split(",")]
for extra in extras_list:
if extra != "" and extra not in ["info"]:
await ctx.send(f"Unrecognised extra `{extra}`.\nPlease choose from `info`.", hidden=True)
return
try:
# Both will raise ValueError if the user isn't found, get_id_from_username will usually error first.
# In cases where the account was only removed recently, get_user will error.
user_id = get_id_from_username(username)
user = get_user(user_id)
except ValueError as error_message:
await ctx.send(error_message, hidden=True)
return
await ctx.defer()
await ctx.send(embed=user_embed(user, extras_list))
def get_id_from_username_old(username: str) -> int:
whosthat = requests.get(config["whosthat_url"] + "whosthat.php?action=names&q=" + username).json()
if len(whosthat) > 0:
return whosthat[0]["id"]
else:
raise ValueError(f"User `{username}` not found")
def get_id_from_username(username: str) -> int:
whosthat = requests.get(config["whosthat_url"] + "whosthat.php?action=names&q=" + username).json()
if len(whosthat) > 0:
return whosthat[0]["id"]
# Backup solution via changesets
res = requests.get(config["api_url"] + f"api/0.6/changesets/?display_name={username}").text
if res == "Object not found":
raise ValueError(f"User `{username}` does not exist.")
if "uid=" in res:
# +5 and -2 are used to isolate uid from `uid="123" `.
return res[res.find('uid="') + 5 : res.find('user="') - 2]
# Backup of a backup by using notes lookup.
res = requests.get(config["api_url"] + f"api/0.6/notes/search.json/?display_name={username}").json()
for feat in res["features"]:
for comm in feat["properties"]["comments"]:
try:
if comm["user"] == username:
return str(comm["uid"])
except KeyError:
pass # Encountered anonymous note
raise ValueError(f"User `{username}` does exist, but has no changesets nor notes.")
def get_user(user_id: str | int) -> dict:
res = requests.get(config["api_url"] + f"api/0.6/user/{user_id}.json")
try:
user = res.json()["user"]
except (json.decoder.JSONDecodeError, IndexError, KeyError):
raise ValueError(f"User `{user_id}` not found")
return user
def user_embed(user: dict, extras: Iterable[str] = []) -> Embed:
embed = Embed()
embed.type = "rich"
url_safe_user = quote(user["display_name"])
embed.url = config["site_url"] + "user/" + url_safe_user
embed.set_footer(
text=config["copyright_notice"],
icon_url=config["icon_url"],
)
if "img" in user:
embed.set_thumbnail(url=user["img"]["href"])
else:
embed.set_thumbnail(url=config["symbols"]["user"])