~nova/fletcher

fletcher/chronos.py -rw-r--r-- 2.9 KiB
ece10afa — Novalinium f-string issue 9 days ago
                                                                                
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
from sys import exc_info
import logging
from geopy.geocoders import Nominatim
import pytz
import discord
from tzwhere import tzwhere
from datetime import datetime

geolocator = None
tzwheremst = None
logger = logging.getLogger("fletcher")


def time_at_place(message, client, args):
    global ch
    global geolocator
    global tzwheremst
    try:
        q = " ".join(args)
        if len(args) > 0:
            try:
                tz = pytz.timezone(q)
            except pytz.UnknownTimeZoneError as e:
                location = geolocator.geocode(q)
                tz = pytz.timezone(
                    tzwheremst.tzNameAt(location.latitude, location.longitude)
                )
        elif ch.user_config(message.author.id, message.guild.id, "tz"):
            tz = pytz.timezone(
                ch.user_config(message.author.id, message.guild.id, "tz")
            )
        else:
            tz = pytz.utc
        now = datetime.now(tz)
        return f'The time is {now.strftime("%Y-%m-%d %H:%M")} ({tz} time zone).'
    except pytz.UnknownTimeZoneError as e:
        return f"Error: {type(e).__name__} for ({location})"
    except AttributeError as e:
        return "Could not find matching place or time"
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error(f"TAP[{exc_tb.tb_lineno}]: {type(e).__name__} {e}")


def get_tz(message=None, user=None, guild=None):
    global ch
    if message:
        user = message.author
        guild = message.guild
    if user and isinstance(user, discord.User) or isinstance(user, discord.Member):
        user = user.id
    if guild and isinstance(guild, discord.Guild):
        guild = guild.id
    if ch.user_config(user, guild, "tz"):
        tz = pytz.timezone(ch.user_config(message.author.id, message.guild.id, "tz"))
    elif ch.scope_config(guild=guild, channel=message.channel).get("tz"):
        tz = pytz.timezone(
            ch.scope_config(guild=guild, channel=message.channel).get("tz")
        )
    elif ch.scope_config(guild=guild).get("tz"):
        tz = pytz.timezone(ch.scopedconfig(guild=guild).get("tz"))
    else:
        tz = pytz.utc
    return tz


def get_now(message=None, user=None, guild=None):
    return datetime.now(get_tz(message=message, user=user, guild=guild))


def autoload(ch):
    global config
    global geolocator
    global tzwheremst
    if not geolocator:
        geolocator = Nominatim(
            user_agent=config.get("discord", dict()).get("botLogName", "botLogName")
        )
    if not tzwheremst:
        tzwheremst = tzwhere.tzwhere()
    ch.add_command(
        {
            "trigger": ["!now", "!time"],
            "function": time_at_place,
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": ["[place name]"],
            "description": "Current time (at optional location)",
        }
    )


async def autounload(ch):
    pass