DeepBlue/cogs/fun/autoconvert.py

76 lines
2.4 KiB
Python
Raw Normal View History

2020-01-08 01:26:36 +00:00
'''
Listens for certain keywords in messages and
then provides conversion charts that might be
useful.
'''
2020-01-07 17:04:00 +00:00
import discord
from discord.ext import commands
2020-01-08 01:08:07 +00:00
from util import logging, checking, config
2020-01-07 17:04:00 +00:00
import re
class AutoConvert(commands.Cog):
2020-01-08 01:26:36 +00:00
def __init__(self, client: discord.Client):
2020-01-07 17:04:00 +00:00
self.client = client
self.currencies = ['', '$', '£']
self.currency_conversion = {
"€$":1.1144,
"€£":0.85
}
'''
Checks wether a message contains currency symbols
Returns an array of prices found
, $, £
'''
def contains_currency(self, message : discord.Message) -> []:
prices = []
words = message.content.split(' ')
for word in words:
for currency in self.currencies:
if currency in word:
try:
prices.append([float(re.findall(r"[-+]?\d*\.\d+|\d+", word)[0]), currency])
except:
pass
break
return prices
2020-01-08 01:26:36 +00:00
def convert_currency(self, _from: str, to: str, value: float) -> float:
2020-01-07 17:04:00 +00:00
if _from == '':
conversion_rate = self.currency_conversion[_from + to]
elif to == '':
conversion_rate = 1/self.currency_conversion[to + _from]
else:
conversion_rate = self.currency_conversion['' + to] / self.currency_conversion['' + _from]
return round(value * conversion_rate, 2)
@commands.Cog.listener()
2020-01-08 01:26:36 +00:00
async def on_message(self, message: discord.Message):
2020-01-07 17:04:00 +00:00
if message.author.bot:
return
empty = True
currencies = self.contains_currency(message)
2020-01-08 01:08:07 +00:00
embed = discord.Embed(title="Here are some useful conversions:", color=int(config.settings["color"], 16))
2020-01-07 17:04:00 +00:00
if len(currencies) != 0:
empty = False
for element in currencies:
currency_string = ""
for currency in self.currencies:
if currency == element[1]:
continue
currency_string += f"{self.convert_currency(element[1], currency, element[0])}{currency}, "
embed.add_field(name=str(element[0])+element[1], value=currency_string[:-2])
if not empty:
await message.channel.send(embed=embed)
2020-01-08 01:26:36 +00:00
def setup(client: discord.Client):
2020-01-07 17:04:00 +00:00
client.add_cog(AutoConvert(client))