Advertisement
throb

Simple timezone converstion bot

Jan 11th, 2023 (edited)
969
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.49 KB | Source Code | 1 0
  1. import discord
  2. import pytz, json, os
  3. from pytz import all_timezones
  4. from datetime import datetime, timedelta
  5. from dateutil.parser import parse
  6. import re
  7.  
  8. # Create a new discord client
  9. client = discord.Client(intents=discord.Intents.all())
  10.  
  11. # Dictionary to store users' timezones
  12. timezones = {}
  13. jsonDir = os.path.dirname(os.path.realpath(__file__))
  14. jsonPath = os.path.join(jsonDir,'timezones.json')
  15. # Load timezones from json file
  16. try :
  17.     with open(jsonPath, 'r') as f:
  18.         timezones = json.load(f)
  19.         #convert the string keys to int
  20.         timezones = {int(k): v for k, v in timezones.items()}
  21. except:
  22.     pass
  23.  
  24. @client.event
  25.  
  26. async def on_message(message):
  27.  
  28.     if message.author.bot == False:
  29.  
  30.             # Check if message starts with "/settz" command
  31.         if message.content.startswith('/settz'):
  32.             # Get the timezone from the message
  33.             tz = message.content[7:]
  34.             # Check if the timezone is a valid one
  35.             if tz in all_timezones:
  36.                 # Store the user's timezone in the dictionary
  37.                 authID = int(message.author.id)
  38.                 timezones[authID] = tz
  39.                 # Send confirmation message to user
  40.                 await message.channel.send(f'Timezone set to {tz}')
  41.                 # Save timezones to json file
  42.                 with open(jsonPath, 'w') as f:
  43.                     json.dump(timezones, f)
  44.                     # print(timezones)
  45.  
  46.             else:
  47.                 # Send error message if timezone is not valid
  48.                 await message.channel.send('Invalid timezone')
  49.  
  50.         # Check if message starts with "/gettz" command
  51.         if message.content.startswith('/gettz'):
  52.             # Retrieve user's timezone from dictionary
  53.             # print(timezones)
  54.             tz = timezones.get(message.author.id)
  55.             if tz is None:
  56.                 # Send message if user's timezone is not set
  57.                 await message.channel.send('Timezone not set')
  58.             else:
  59.                 # Send message with user's timezone
  60.                 await message.channel.send(f'Timezone is {tz}')
  61.  
  62.         # Check if message starts with "/time" command
  63.     if message.content.startswith("/time"):
  64.         input_time = message.content[6:]
  65.         # Try to parse the input time using dateutil
  66.         try:
  67.             parsed_time = parse(input_time)
  68.             tz = timezones.get(message.author.id)
  69.             if tz is None:
  70.                 # Send message if user's timezone is not set
  71.                 await message.channel.send('Timezone not set')
  72.             else:
  73.                 # Add timezone information to parsed time
  74.                 aware_time = pytz.timezone(tz).localize(parsed_time)
  75.                 parsed_time = parsed_time.replace(tzinfo=pytz.timezone(tz))
  76.  
  77.                 # Get the Unix time
  78.                 unix_time = int(parsed_time.timestamp())
  79.        
  80.                 dt_object = datetime.fromtimestamp(unix_time)
  81.  
  82.                 # Define the time zones
  83.                 munich_tz = pytz.timezone("Europe/Prague")
  84.                 melbourne_tz = pytz.timezone("Australia/Melbourne")
  85.                 austin_tz = pytz.timezone("US/Central")
  86.                 detroit_tz = pytz.timezone("US/Eastern")
  87.                 los_angeles_tz = pytz.timezone("US/Pacific")
  88.  
  89.                 # Convert the datetime object to the respective time zones
  90.                 munich_time = aware_time.astimezone(munich_tz)
  91.                 melbourne_time = aware_time.astimezone(melbourne_tz)
  92.                 austin_time = aware_time.astimezone(austin_tz)
  93.                 detroit_time = aware_time.astimezone(detroit_tz)
  94.                 los_angeles_time = aware_time.astimezone(los_angeles_tz)
  95.  
  96.  
  97.                 # Define the time format
  98.                 timeFormat = "%a %b %d %I:%M %p"
  99.                 # Send the converted times back to the channel
  100.                 await message.channel.send(f"`ATX: {austin_time.strftime(timeFormat)}`")
  101.                 await message.channel.send(f"`LAX: {los_angeles_time.strftime(timeFormat)}`")
  102.                 await message.channel.send(f"`MUN: {munich_time.strftime(timeFormat)}`")
  103.                 await message.channel.send(f"`MLB: {melbourne_time.strftime(timeFormat)}`")
  104.                 await message.channel.send(f"`MTL: {detroit_time.strftime(timeFormat)}`")
  105.  
  106.         # Send error message if input time is not valid      
  107.         except ValueError:
  108.             await message.channel.send("Invalid input time. Please use a human-readable format like 'Jan 12 1pm'.\nNote that you have to use 2:30pm vs 230pm")
  109.             return                
  110.     else:
  111.         times = re.findall(r'\b(1[0-2]|0?[1-9]):?([0-5][0-9])? ?([ap]m)\b', message.content)
  112.         datetime_obj = None
  113.         for time in times:
  114.             # await message.channel.send(time)
  115.             if time[1] == '':
  116.                 timeString = f'{time[0]}00{time[2]}'
  117.             else:
  118.                 timeString = f'{time[0]}{time[1]}{time[2]}'
  119.  
  120.             datetime_obj = datetime.strptime(timeString, "%I%M%p")
  121.  
  122.             formatted_time = datetime_obj.strftime("%I:%M %p")
  123.             if formatted_time[:1] == '0':
  124.                 formatted_time = formatted_time[1:]
  125.  
  126.             # await message.channel.send(formatted_time)
  127.             try:
  128.                 parsed_time = parse(formatted_time)
  129.                 tz = timezones.get(message.author.id)
  130.                 if tz is None:
  131.                     # Send message if user's timezone is not set
  132.                     await message.channel.send('Timezone not set')
  133.                 else:
  134.                     # Add timezone information to parsed time
  135.                     aware_time = pytz.timezone(tz).localize(parsed_time)
  136.                     parsed_time = parsed_time.replace(tzinfo=pytz.timezone(tz))
  137.  
  138.                     # Get the Unix time
  139.                     unix_time = int(parsed_time.timestamp())
  140.            
  141.                     dt_object = datetime.fromtimestamp(unix_time)
  142.  
  143.                     # Define the time zones
  144.                     munich_tz = pytz.timezone("Europe/Prague")
  145.                     melbourne_tz = pytz.timezone("Australia/Melbourne")
  146.                     austin_tz = pytz.timezone("US/Central")
  147.                     detroit_tz = pytz.timezone("US/Eastern")
  148.                     los_angeles_tz = pytz.timezone("US/Pacific")
  149.  
  150.                     # Convert the datetime object to the respective time zones
  151.                     munich_time = aware_time.astimezone(munich_tz)
  152.                     melbourne_time = aware_time.astimezone(melbourne_tz)
  153.                     austin_time = aware_time.astimezone(austin_tz)
  154.                     detroit_time = aware_time.astimezone(detroit_tz)
  155.                     los_angeles_time = aware_time.astimezone(los_angeles_tz)
  156.  
  157.  
  158.                     # Define the time format
  159.                     timeFormat = "%I:%M %p"
  160.                     # Send the converted times back to the channel
  161.                     await message.channel.send(f"`ATX: {austin_time.strftime(timeFormat)} | LAX: {los_angeles_time.strftime(timeFormat)} | MUN: {munich_time.strftime(timeFormat)} | MLB: {melbourne_time.strftime(timeFormat)} | MTL: {detroit_time.strftime(timeFormat)}`")
  162.  
  163.             # Send error message if input time is not valid      
  164.             except ValueError:
  165.                 await message.channel.send("Invalid input time. Please use a human-readable format like 'Jan 12 1pm'.\nNote that you have to use 2:30pm vs 230pm")
  166.                 return
  167.            
  168.        
  169.  
  170.  
  171.  
  172. client.run('TOKEN')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement