Пример #1
0
def fetch_exchange_rates(
    target_currency: str,
    currencies: Iterable[str],
    amount: float = 1.0,
    bitcoin_proxy: str = 'USD',
) -> Dict[str, Optional[float]]:
    """
    Given an amount and a base currency, returns the exchange rates for a set
    of currencies.
    """
    rates: Dict[str, Optional[float]] = {}
    rates_select: Dict[str, Optional[float]] = {}
    is_bitcoin: bool = False

    # Special case if base currency is BitCoin
    if target_currency == 'BTC':
        is_bitcoin = True
        target_currency = bitcoin_proxy

    # Instantiate converter
    converter = CurrencyRates()
    converter_btc = BtcConverter()

    # Get rates for base currency

    try:
        rates = converter.get_rates(target_currency)
    except ConnectionError:
        logger.warning(
            f"Could not connect to currency rates service. No exchange rates " \
            f"available."
        )
        return rates_select

    # Get Bitcoin rate for base currency
    try:
        rates['BTC'] = converter_btc.convert_to_btc(amount=amount,
                                                    currency=bitcoin_proxy)
    except ConnectionError:
        logger.warning(
            f"Could not connect to currency rates service. No BitCoin " \
            f"exchange rate available."
        )
        return rates_select

    # Select rates
    for currency in currencies:
        if currency in rates:
            rates_select[currency] = rates[currency]
        else:
            rates_select[currency] = None

    # Convert to base BitCoin if BitCoin was base currency
    if is_bitcoin:
        rate_btc = rates_select['BTC']
        for currency in rates_select.keys():
            if rates_select[currency]:
                rates_select[currency] = rates_select[currency] / rate_btc

    return rates_select
Пример #2
0
def arcturus_cal(money, arcturus_rate, c_type, bonus=0):
    c = CurrencyRates()
    b = BtcConverter()
    print(c_type)
    if c_type == "USD":
        if int(money) >= 100:
            usd = float(money)
            no_of_btc = b.convert_to_btc(usd, 'USD')
            return {"no_of_arcturus": float(usd) / float(arcturus_rate)}
        else:
            return {
                "no_of_arcturus":
                "Error... Minimum transaction should be more then 100 usd"
            }
    elif c_type.upper() == "BTC":
        usd = b.convert_btc_to_cur(float(money), 'USD')
        if int(usd) >= 100:
            usd = float(usd)
            return {"no_of_arcturus": float(usd) / float(arcturus_rate)}
        else:
            return {
                "no_of_arcturus":
                "Minimum transaction should be more then 100 usd"
            }
    else:
        return {"no_of_arcturus": "Usupported cryptotype.... "}
Пример #3
0
 def getexchange(self, message=None, match=None, to=None):
     amount = match.group("amount")
     price = BtcConverter()
     return TextMessageProtocolEntity(
         amount + " INR = " +
         str(price.convert_to_btc(int(amount), 'BTC')) + " INR",
         to=message.getFrom())
Пример #4
0
def convert(c1, c2, amount):
    try:
        if amount == "":
            messagebox.showerror("Error", "Amount not specified")
        elif c1 == "Select" or c2 == "Select":
            messagebox.showinfo("Error", "Currency not selected")
        else:
            try:
                amount = float(amount)
                b = BtcConverter()
                c = CurrencyRates()
                if c1 == c2:
                    result = amount
                elif c1 == "BTC":
                    result = b.convert_btc_to_cur(amount, c2)
                elif c2 == "BTC":
                    result = b.convert_to_btc(amount, c1)
                else:
                    result = c.convert(c1, c2, int(amount))
                print(result)
                label_down[
                    "text"] = f"Conversion Result: {amount} {c2}\n{amount} {c1} = {result} {c2}"
            except ValueError:
                messagebox.showerror("Error", "Invalid amount")
                clear()
    except Exception:
        messagebox.showerror("Error", "Please try again")
Пример #5
0
    async def currency_to_bitcoin(self, ctx, amount, currency="USD"):
        try:
            b = BtcConverter()
            amount = int(amount)
        except:
            embed = discord.Embed(color=self.bot.embed_color,
                                  title="→ Money Error!",
                                  description="• Not a valid amount of money!")
            await ctx.send(embed=embed)
        try:
            btc = round(b.convert_to_btc(amount, currency), 4)
        except:
            embed = discord.Embed(
                color=self.bot.embed_color,
                title="→ Currency Error!",
                description="• Not a valid currency!"
                "\n• Example: `l!tobtc 10 CAD`"
                "\n• Pro Tip: `If you use USD currency, you do not have to specify the currency in the command.`"
            )
            await ctx.send(embed=embed)
        embed = discord.Embed(
            color=self.bot.embed_color,
            title="→ Currency To Bitcoin!",
            description=f"• {amount} {currency} is around {btc} Bitcoin!")

        await ctx.send(embed=embed)

        logger.info(f"Utility | Sent Currency_To_btc: {ctx.author}")
Пример #6
0
 async def execute(self, args, msg):
     amount, origin, destination = args
     try:
         amount = Decimal(amount)
     except Exception as _:
         raise ValueError(f'Cannot parse decimal: {amount}')
     try:
         o_code, o_symbol = self.currency_code_and_symbol(origin)
     except TypeError:
         raise ValueError(f'Unknown currency: {origin}')
     try:
         d_code, d_symbol = self.currency_code_and_symbol(destination)
     except TypeError:
         raise ValueError(f'Unknown currency: {destination}')
     c = CurrencyRates()
     if o_code == 'BTC':
         b = BtcConverter()
         res = b.convert_btc_to_cur(amount, 'USD')
         if d_code != 'USD':
             res = c.convert('USD', d_code, res)
     elif d_code == 'BTC':
         b = BtcConverter()
         if o_code != 'USD':
             amount = c.convert(o_code, 'USD', amount)
         res = b.convert_to_btc(amount, o_code)
     else:
         res = c.convert(o_code, d_code, amount)
     res = self.format_number(res, 4, 2)
     await msg.channel.send(f'{amount: f} {o_code} = {res or 0} {d_code}')
def convert(amount, input_currency, output_currency):
    input_currency_code = get_currency_code(input_currency)
    if input_currency_code is None:  # Input currency code was not found - unknown currency
        raise UnknownCurrencyError

    if output_currency is not None:
        output_currency_code = get_currency_code(output_currency)
        if output_currency_code is None:  # Output currency code was not found - unknown currency
            raise UnknownCurrencyError
        currency_data = [{'cc': output_currency_code}]
    else:
        # Getting currency data from file
        currency_data = get_currency_data()

    c = CurrencyRates()
    b = BtcConverter()
    output_currencies = dict(
    )  # Dictionary to store converted amounts for each currency

    # Converting currency
    for item in currency_data:
        if item['cc'] == input_currency_code:  # Out currency == in currency
            if output_currency is None:
                continue
            else:
                raise SameCurrencyError

        try:
            if input_currency_code == "BTC":  # Bitcoin is input currency
                output_currencies[item['cc']] = round(
                    b.convert_btc_to_cur(amount, item['cc']), 2)

            elif item['cc'] == "BTC":  # Bitcoin is output currency
                output_currencies[item['cc']] = round(
                    b.convert_to_btc(amount, input_currency_code), 5)

            else:  # Other currencies than bitcoin
                output_currencies[item['cc']] = round(
                    c.convert(input_currency_code, item['cc'], amount), 2)

        except RatesNotAvailableError:
            if output_currency is None:  # Output currency not entered, currencies without available rates are skipped
                pass
            else:  # Output currency entered => not available currency rate yields error
                raise RatesNotAvailableError

    output_data = dict()
    output_data['input'] = {'amount': amount, 'currency': input_currency_code}
    output_data['output'] = output_currencies

    return json.dumps(output_data, indent='\t')
Пример #8
0
def convert(currency, amount):

    # create a new converter object with standardized date
    b = BtcConverter()
    x = b.get_latest_price(currency)

    cprint('Powered by Coindesk | https://www.coindesk.com/price/', 'green')
    print("[" + str(dts) + "]" + "  " + currency.upper() +
          " for 1.0 Bitcoin (BTC) is " + str(x))

    # convert to BTC
    conversion_amount = b.convert_to_btc(amount, currency.upper())
    print(
        "[{}]  Converting {} to BTC: {} {} is currently worth {} BTC!".format(
            str(dts), currency.upper(), "%0.2f" % (amount), currency.upper(),
            conversion_amount))
Пример #9
0
    def currencyconv(self, jarvis, amount, fr, to):
        """
        currencyconv converts the given amount to another currency
        using fore-python
        """

        b = BtcConverter(force_decimal=True)
        c = CurrencyRates(force_decimal=True)

        if (to == "BTC"):
            result = b.convert_to_btc(Decimal(amount), fr)
        elif (fr == "BTC"):
            result = b.convert_btc_to_cur(Decimal(amount), to)
        else:
            result = c.convert(fr, to, Decimal(amount))

        jarvis.say(str(result))
Пример #10
0
 def currencyconverter(self):
     global audresp
     currency1 = audresp.currenciesinspeech[0].replace("£", "GBP").replace("$", "USD").replace("dollars",
                                                                                               "USD").replace(
         "pounds", "GBP")
     currency2 = audresp.currenciesinspeech[1].replace("£", "GBP").replace("$", "USD").replace("dollars",
                                                                                               "USD").replace(
         "pounds", "GBP")
     amount = audresp.numbers[0]
     crypto = ["bitcoin", "litcoin"]
     if currency2 == "bitcoin":
         b = BtcConverter()
         return str(b.convert_to_btc(amount, currency1)) + " btc"
     else:
         c = CurrencyRates()
         convertion = c.convert(currency1, currency2, amount)
         return currency2.replace("GBP", "£").replace("USD", "$") + str(convertion)
Пример #11
0
    def currencyconv(self, jarvis, amount, fr, to):
        """
        currencyconv converts the given amount to another currency
        using fore-python
        """

        b = BtcConverter(force_decimal=True)
        c = CurrencyRates(force_decimal=True)

        if (to == "BTC"):
            result = b.convert_to_btc(Decimal(amount), fr)
        elif (fr == "BTC"):
            result = b.convert_btc_to_cur(Decimal(amount), to)
        else:
            result = c.convert(fr, to, Decimal(amount))
        outputText = str(amount) + " " + fr + \
            " are equal to " + str(result) + " " + to
        jarvis.say(outputText)
Пример #12
0
class TestBitCoinForceDecimal(TestCase):
    def setUp(self):
        self.b = BtcConverter(force_decimal=True)

    def test_latest_price_valid_currency(self):
        price = self.b.get_latest_price('USD')
        self.assertEqual(type(price), Decimal)

    def test_latest_price_invalid_currency(self):
        price = self.b.get_latest_price('XYZ')
        self.assertFalse(price)

    def test_previous_price_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        price = self.b.get_previous_price('USD', date_obj)
        self.assertEqual(type(price), Decimal)

    def test_previous_price_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.get_previous_price,
                          'XYZ', date_obj)

    def test_previous_price_list_with_valid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('USD', start_date,
                                                    end_date)
        self.assertTrue(price_list)
        self.assertEqual(type(price_list), dict)

    def test_previous_price_list_with_invalid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('XYZ', start_date,
                                                    end_date)
        self.assertFalse(price_list)
        self.assertEqual(type(price_list), dict)

    def test_convet_to_btc_with_valid_currency(self):
        coins = self.b.convert_to_btc(Decimal('250'), 'USD')
        self.assertEqual(type(coins), Decimal)

    def test_convet_to_btc_with_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc,
                          Decimal('250'), 'XYZ')

    def test_convert_btc_to_cur_valid_currency(self):
        amount = self.b.convert_btc_to_cur(Decimal('2'), 'USD')
        self.assertEqual(type(amount), Decimal)

    def test_convert_btc_to_cur_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur,
                          Decimal('250'), 'XYZ')

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        coins = self.b.convert_to_btc_on(Decimal('300'), 'USD', date_obj)
        self.assertEqual(type(coins), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc_on,
                          Decimal('250'), 'XYZ', date_obj)

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        amount = self.b.convert_btc_to_cur_on(Decimal('250'), 'USD', date_obj)
        self.assertEqual(type(amount), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur_on,
                          Decimal('3'), 'XYZ', date_obj)
#!/usr/bin/env python
# This program buys some Dogecoins and sells them for a bigger price

import sys
sys.path.append('../../')

from Trader.Bittrex3 import Bittrex3
from forex_python.bitcoin import BtcConverter
import json

b = BtcConverter()

latestBitcoinPrice = b.get_latest_price('USD')
print("Latest Bitcoin Price " + str(latestBitcoinPrice))

dollarsToUSD = b.convert_to_btc(1, "USD")
print("1 USD to bitcoin " + str(dollarsToUSD))


def bitcoin_to_USD(amount):
    b = BtcConverter()
    latest_price = b.get_latest_price('USD')
    return latest_price * amount


print(bitcoin_to_USD(0.00122808))

# Get these from https://bittrex.com/Account/ManageApiKey

with open("secrets.json") as secrets_file:
    secrets = json.load(secrets_file)
Пример #14
0
from_currency = input('From : ').upper()
to_currency = input('To : ').upper()

print('\n' + from_currency + " To " + to_currency, amount)
print('The current conversion rate for {} to {} is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency)))    #Get conversion rate from USD to INR
result = c.convert(from_currency, to_currency, amount)   #Convert the amount
print('Latest Conversion: ',result)

#Get conversion rate as of 2021-01-01
print('\nThe conversion rate from {} to {} as per 1st Jan 2021 is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency, date_obj)))
print('The conversion as per 1st Jan 2021: ', c.convert(from_currency, to_currency, amount, date_obj))

b = BtcConverter()
print('\n\nBitcoin Symbol: ', b.get_symbol())  # get_btc_symbol()
print('Bitcoin Latest Price in USD : ', b.get_latest_price('USD'))     #Get latest Bitcoin price.
print('Convert 10 Million USD to Bitcoin', b.convert_to_btc(10000000, 'USD'))     #Convert Amount to Bitcoins based on latest exchange price.
print('The Equivalent of 10.99 Bitcoin in USD: ',b.convert_btc_to_cur(10.99, 'USD'))         #Convert Bitcoins to valid currency amount based on lates price

print('\nBitcoin price as per 1st Jan 2021: ',b.get_previous_price('USD', date_obj)) #Get price of Bitcoin based on prevois date
print('The conversion of 10 Million Dollars to Bitcoin as of 1st Jan 2021',b.convert_to_btc_on(10000000, 'USD', date_obj))      #Convert Amount to bitcoins based on previous date prices
print('The conversion of 10.99 Bitcoin in USD as of 1st Jan 2021: ',b.convert_btc_to_cur_on(10.99, 'USD', date_obj))       #Convert Bitcoins to valid currency amount based on previous date price

start_date = datetime.datetime(2021, 2, 1, 19, 39, 36, 815417)
end_date = datetime.datetime(2021, 2, 7, 19, 39, 36, 815417)
print('\nBitcoin rates over the week in USD: ',b.get_previous_price_list('USD', start_date, end_date))         #Get list of prices list for given date range

d = CurrencyCodes()
print('\nUS Dollar Symbol:', d.get_symbol('USD'))          #Get currency symbol using currency code
print(d.get_currency_name('USD'))          #Get Currency Name using currency code

print('\nThe latest rate of USD for various currencies\n', c.get_rates('USD'))          #list all latest currency rates for "USD"
from forex_python.converter import CurrencyRates
from forex_python.bitcoin import BtcConverter

converter = CurrencyRates()
amount = int(input("Zadejte požadovanou částku: "))
price_czk = converter.convert('EUR', 'CZK', amount)
print(f"Pro získání {amount} dolarů potřebujete {price_czk} CZK")

btc = BtcConverter()
amount_btc = int(input("Zadejte požadované množství BTC k převodu do CZK: "))
btc.get_latest_price('CZK')
price_czk_btc = btc.convert_to_btc(amount_btc, 'CZK')
print(f"Pro získání {amount_btc} bitcoinu potřebujete {price_czk_btc} CZK")
Пример #16
0
def pullData():
    t = '{:%H:%M:%S}'.format(datetime.datetime.now() +
                             datetime.timedelta(hours=1))
    #t = time.strftime("%H:%M:%S")
    print("Starting at number: " + str(datetime.datetime.utcnow()))
    # Using forex to get latest data: https://media.readthedocs.org/pdf/forex-python/latest/forex-python.pdf
    c = CurrencyRates()
    b = BtcConverter()
    rates = c.get_rates(config.LOCAL_CURR_CODE)
    pop = False

    # Adapted from: https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu
    chart_data['labels'].append(t)
    # If 20 dates are already currently in the list - pop.
    if len(chart_data['labels']) >= 20:
        chart_data['labels'].pop(0)
        pop = True
    # Loop through array of datasets to append or append and pop.
    if chart_data['datasets']:
        for i, code in enumerate(config.CURR_CODES):
            if code == 'BTC':
                price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2)
                rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5)
            else:
                price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2)
                rate = round(rates[chart_data['datasets'][i]['label']], 5)
            chart_data['datasets'][i]['data'].append(price)
            latest_currencies['currencies'][i]['data'] = rate
            if pop:
                chart_data['datasets'][i]['data'].pop(0)
    else:
        co = CurrencyCodes()
        # Prepare data objects and pull first prices.
        for i, code in enumerate(config.CURR_CODES):
            if code == 'BTC':
                symbol = b.get_symbol()
                name = 'Bitcoin'
                price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2)
                rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5)
            else:
                name = co.get_currency_name(code)
                symbol = co.get_symbol(code)
                price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2)
                rate = round(rates[code], 5)
            chart_data['datasets'].append({
                'label':
                code,
                'backgroundColor':
                config.CURR_COLORS[i],
                'data': [price]
            })
            latest_currencies['currencies'].append({
                'code': code,
                'name': name,
                'symbol': symbol,
                'data': rate
            })

    r.set(config.REDIS_CHAN_LIST, latest_currencies)
    r.set(config.REDIS_CHAN_GRAPH, chart_data)

    print("Finishing at number: " + str(datetime.datetime.utcnow()))
Пример #17
0
async def on_message(message):
    
    
    
    #Commands
    if not message.author.id == '375343366126436355' and message.content.startswith('!'):
        
        
        
        #Bool checks
        purgecheck = 'placeholder'
        
        
        
        #Help Commands
        if message.content.startswith ('!help'):
            embed = discord.Embed(title='Help', description='Subcommands for help on categories.')
            embed.add_field(name='!help', value='Shows this message.', inline=True)
            embed.add_field(name='!rolehelp', value='Role System Commands', inline=True)
            embed.add_field(name='!adminhelp', value='Admin-only commands.', inline=True)
            embed.add_field(name='!mischelp', value='Miscellaneous Commands.', inline=True)
            embed.add_field(name='Twitter Updates:', value='https://twitter.com/discord_pi_bot')
            embed.set_footer(text='Use !help, !rolehelp, !adminhelp, or !mischelp for other commands.')
            await bot.send_message(message.channel, embed=embed)
        elif message.content.startswith('!rolehelp'):
            embed = discord.Embed(title='!role Subcommands', description='A list of roles members can choose between.')
            embed.add_field(name='!role', value='Subcommands:\nview - Sends the list\nset - Gives you the role you specify in the list (NOT @mention).\nAdmin-only Subcommands:\nadd - Adds the @mentioned role to the list.\nremove - Removes the @mentioned role from the list.\nclear - Clears the list.', inline=False)
            embed.set_footer(text='Use !help, !rolehelp, !adminhelp, or !mischelp for other commands.')
            await bot.send_message(message.channel, embed=embed)
        elif message.content.startswith('!adminhelp'):
            embed = discord.Embed(title='Admin-Only Commands', description='Only members with the Administrator permission can use these commands.')
            embed.add_field(name='!purge', value='Mass deletes messages. Ex: !purge 20', inline=False)
            embed.add_field(name='!addroles', value='Adds roles you specify to a list of roles, members can assign themselves one of them with !setrole. Ex: !addroles @role1 @role2', inline=False)
            embed.add_field(name='!autoassign', value='Adds a role to be automatically assigned to a user when they join.\nSubcommands:\nview - Shows the autoassign list.\nadd - adds the @mentioned roles to the list.\nremove - removes the @mentioned roles from the list.\nclear - Clears the list.', inline=False)
            embed.set_footer(text='Use !help, !rolehelp, !adminhelp, or !mischelp for other commands.')
            await bot.send_message(message.channel, embed=embed)
        elif message.content.startswith('!mischelp'):
            embed = discord.Embed(title='Miscellaneous Commands', description='Commands that don\'t fall under any !help category')
            embed.add_field(name='!lfg', value='Adds or removes you from the "Looking for game" list in that channel.', inline=False)
            embed.add_field(name='!lfg list', value='Shows the "Looking for game" list in that channel.', inline=False)
            embed.add_field(name='!btc', value='Sends the Bitcoin Exchange rate.', inline=False)
            embed.add_field(name='!pfp', value='Gets the profile picture of the @mentioned user.', inline=False)
            embed.set_footer(text='Use !help, !rolehelp, !adminhelp, or !mischelp for other commands.')
            await bot.send_message(message.channel, embed=embed)
            
        
        
        
        if not message.channel.is_private:
            
            
            
            #Dev Commands
            if message.author.id == 'YOUR ID HERE':
                if message.content.startswith('!setstatus'):
                    status = message.content[11:len(message.content)]
                    with open('status.txt', 'w') as f_o:
                        f_o.write(status)
                    await bot.change_presence(game=discord.Game(name=status), status=None, afk=False)
                    await bot.send_message(message.channel, message.author.mention + ' changed status to ' + status)
                elif message.content.startswith('!say'):
                    await bot.send_message(message.channel, message.content.replace('!say ', '', 1))
                elif message.content.startswith('!send'):
                    channel = message.content[0:24].replace('!send ', '', 1)
                    await bot.send_message(bot.get_channel(channel), message.content[25:len(message.content)])
                elif message.content.startswith('!servers'):
                    msg = ''
                    for item in bot.servers:
                        msg = msg + item.name + ' ' + str(len(item.members)) + '\n'
                    await bot.send_message(message.channel, msg)
                elif message.content.startswith('!announcement'):
                    for server in bot.servers:
                        for channel in server.channels:
                            if channel.type == discord.ChannelType.text:
                                if channel.permissions_for(server.me).send_messages:
                                    if channel.name == 'general':
                                        embed=discord.Embed(title='Message From Developer ' + message.author.name, description=message.content.replace('!announcement ', '', 1))
                                        await bot.send_message(channel, embed=embed)
                                        break
            
            
            
            #Administrator-Only Commands
            if message.author.server_permissions.administrator or message.author.id == '268138118270418954':
                if message.content.startswith('!purge'):
                    if int(message.content[7:10]) == 0:
                        await bot.send_message(message.channel, message.author.mention + ' Cannot delete 0 messages.')
                    else:
                        purgecheck = 'a'
                        await bot.delete_message(message)
                        deleted = await bot.purge_from(message.channel, limit=int(message.content[7:10]), check=None)
                        await bot.send_message(message.channel, message.author.mention + ' Successfully deleted {} message(s).'.format(len(deleted)))
                elif message.content.startswith('!autoassign'):
                    if message.content[12:16] == 'view':
                        if not os.path.isfile('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt'):
                            await bot.send_message(message.channel, message.author.mention + ' The autoassign list is empty.')
                        else:
                            with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'r') as f_o:
                                fileline = f_o.readline()
                            rolelist = ''
                            for item in message.server.roles:
                                if item.id in fileline:
                                    rolelist = rolelist + item.name + '\n'
                            embed = discord.Embed(title='Autoassign List:', description=rolelist)
                            embed.set_footer(text='Requested by ' + message.author.name)
                            await bot.send_message(message.channel, embed=embed)
                    elif message.content[12:17] == 'clear':
                        if os.path.isfile('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt'):
                            os.remove('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt')
                            await bot.send_message(message.channel, message.author.mention + ' Cleared autoassign list.')
                        else:
                            await bot.send_message(message.channel, message.author.mention + ' The autoassign list is already empty.')
                    elif message.content[12:15] == 'add':
                        if len(message.role_mentions) == 0:
                            await bot.send_message(message.channel, message.author.mention + ' Make sure to mention the role(s) to add.')
                        else:
                            if not os.path.isfile('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt'):
                                with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'w') as f_o:
                                    f_o.write('')
                            with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'r') as f_o:
                                fileline = f_o.readline()
                            with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'w') as f_o:
                                for item in message.role_mentions:
                                    fileline = fileline + item.id + 'x'
                                f_o.write(fileline)
                            addedroles = ''
                            for item in message.role_mentions:
                                if item.id in fileline:
                                    addedroles = addedroles + item.name + ' '
                            rolelist = ''
                            for item in message.server.roles:
                                if item.id in fileline:
                                    rolelist = rolelist + item.name + '\n'
                            embed = discord.Embed(title='Autoassign List:', description=rolelist)
                            embed.add_field(name='Added Roles:', value=addedroles, inline=False)
                            embed.set_footer(text='Requested by ' + message.author.name)
                            await bot.send_message(message.channel, embed=embed)
                    elif message.content[12:18] == 'remove':
                        if not os.path.isfile('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt'):
                            await bot.send_message(message.channel, message.author.mention + ' The autoassign list is empty.')
                        else:
                            with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'r') as f_o:
                                fileline = f_o.readline()
                            removedroles = ''
                            for item in message.role_mentions:
                                if item.id in fileline:
                                    fileline = fileline.replace(item.id + 'x', '', 1)
                                    removedroles = removedroles + item.name + ' '
                            if fileline == '':
                                os.remove('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt')
                                await bot.send_message(message.channel, message.author.mention + ' Cleared autoassign list.')
                            else:
                                if removedroles == '':
                                    await bot.send_message(message.channel, message.author.mention + ' Mentioned roles aren\'t in the list.')
                                else:
                                    with open('/home/pi/pi_bot/autoassign/' + message.server.id + '.txt', 'w') as f_o:
                                        f_o.write(fileline)
                                    rolelist = ''
                                    for item in message.server.roles:
                                        if item.id in fileline:
                                            rolelist = rolelist + item.name + '\n'
                                    embed = discord.Embed(title='Autoassign List:', description=rolelist)
                                    embed.add_field(name='Removed Roles:', value=removedroles, inline=False)
                                    embed.set_footer(text='Requested by ' + message.author.name)
                                    await bot.send_message(message.channel, embed=embed)
                    else:
                        embed = discord.Embed(title='Not a valid subcommand')
                        embed.add_field(name='!autoassign (Subcommand)', value='view - Shows the autoassign list.\nadd - adds the @mentioned roles to the list.\nremove - removes the @mentioned roles from the list.\nclear - Clears the list.', inline=False)
                        embed.set_footer(text='Requested by ' + message.author.name)
                        await bot.send_message(message.channel, embed=embed)
                
                
            
            
            #Role Commands
            if message.content.startswith('!role') and not message.content.startswith('!rolehelp'):
                if message.content[6:10] == 'view':
                    if not os.path.isfile('/home/pi/pi_bot/roles/' + message.server.id + '.txt'):
                        await bot.send_message(message.channel, message.author.mention + ' The role list is empty.')
                    else:
                        with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'r') as f_o:
                            fileline = f_o.readline()
                        rolelist = ''
                        for item in message.server.roles:
                            if item.id in fileline:
                                rolelist = rolelist + item.name + '\n'
                        embed = discord.Embed(title='Role List:', description=rolelist)
                        embed.set_footer(text='Requested by ' + message.author.name)
                        await bot.send_message(message.channel, embed=embed)
                elif message.content[6:9] == 'set':
                    if not os.path.isfile('/home/pi/pi_bot/roles/' + message.server.id + '.txt'):
                        await bot.send_message(message.channel, message.author.mention + ' The role list is empty.')
                    else:
                        rolelist = await bot.get_server_roles(message.server)
                        removerole = ''
                        real = False
                        for role in rolelist:
                            if role in message.author.roles:
                                removerole = role
                            if role.name == message.content.replace('!role set ', '', 1):
                                setrole = role
                                real = True
                        if real == False:
                            await bot.send_message(message.channel, message.author.mention + ' That role doesn\'t exist, use !rolehelp for help.')
                        else:
                            embed = discord.Embed(title='Set role to:', description=setrole.name)
                            if not removerole == '':
                                await bot.remove_roles(message.author, removerole)
                                embed.add_field(name='Removed role:', value=removerole.name, inline=True)
                            embed.set_footer(text='Requested by ' + message.author.name)
                            await bot.add_roles(message.author, setrole)
                            await bot.send_message(message.channel, embed=embed)
                elif message.author.server_permissions.administrator or message.author.id == '268138118270418954':
                    if message.content[6:11] == 'clear':
                        if os.path.isfile('/home/pi/pi_bot/roles/' + message.server.id + '.txt'):
                            os.remove('/home/pi/pi_bot/roles/' + message.server.id + '.txt')
                            await bot.send_message(message.channel, message.author.mention + ' Cleared role list.')
                        else:
                            await bot.send_message(message.channel, message.author.mention + ' The role list is already empty.')
                    elif message.content[6:9] == 'add':
                        if len(message.role_mentions) == 0:
                            await bot.send_message(message.channel, message.author.mention + ' Make sure to mention the role(s) to add.')
                        else:
                            if not os.path.isfile('/home/pi/pi_bot/roles/' + message.server.id + '.txt'):
                                with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'w') as f_o:
                                    f_o.write('')
                            with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'r') as f_o:
                                fileline = f_o.readline()
                            with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'w') as f_o:
                                for item in message.role_mentions:
                                    fileline = fileline + item.id + 'x'
                                f_o.write(fileline)
                            addedroles = ''
                            for item in message.role_mentions:
                                if item.id in fileline:
                                    addedroles = addedroles + item.name + ' '
                            rolelist = ''
                            for item in message.server.roles:
                                if item.id in fileline:
                                    rolelist = rolelist + item.name + '\n'
                            embed = discord.Embed(title='Role List:', description=rolelist)
                            embed.add_field(name='Added Roles:', value=addedroles, inline=False)
                            embed.set_footer(text='Requested by ' + message.author.name)
                            await bot.send_message(message.channel, embed=embed)
                    elif message.content[6:12] == 'remove':
                        if not os.path.isfile('/home/pi/pi_bot/roles/' + message.server.id + '.txt'):
                            await bot.send_message(message.channel, message.author.mention + ' The role list is empty.')
                        else:
                            with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'r') as f_o:
                                fileline = f_o.readline()
                            removedroles = ''
                            for item in message.role_mentions:
                                if item.id in fileline:
                                    fileline = fileline.replace(item.id + 'x', '', 1)
                                    removedroles = removedroles + item.name + ' '
                            if fileline == '':
                                os.remove('/home/pi/pi_bot/roles/' + message.server.id + '.txt')
                                await bot.send_message(message.channel, message.author.mention + ' Cleared role list.')
                            else:
                                if removedroles == '':
                                    await bot.send_message(message.channel, message.author.mention + ' Mentioned roles aren\'t in the list.')
                                else:
                                    with open('/home/pi/pi_bot/roles/' + message.server.id + '.txt', 'w') as f_o:
                                        f_o.write(fileline)
                                    rolelist = ''
                                    for item in message.server.roles:
                                        if item.id in fileline:
                                            rolelist = rolelist + item.name + '\n'
                                    embed = discord.Embed(title='Role List:', description=rolelist)
                                    embed.add_field(name='Removed Roles:', value=removedroles, inline=False)
                                    embed.set_footer(text='Requested by ' + message.author.name)
                                    await bot.send_message(message.channel, embed=embed)
                    else:
                        embed = discord.Embed(title='Not a valid subcommand')
                        embed.add_field(name='!role (Subcommand)', value='view - Shows the role list.\nadd - adds the @mentioned roles to the list.\nremove - removes the @mentioned roles from the list.\nclear - Clears the list.', inline=False)
                        embed.set_footer(text='Requested by ' + message.author.name)
                        await bot.send_message(message.channel, embed=embed)
            
            
            
            #Misc. Commands
            if message.content.startswith('!lfg'):
                if message.content[5:9] == 'list':
                    if not os.path.isfile('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt'):
                        embed=discord.Embed(title='There is currently no one looking for a game')
                    else:
                        with open('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt', 'r') as f_o:
                            file = f_o.readline()
                        msg = ''
                        for member in message.server.members:
                            if member.id in file:
                                msg = msg + member.name + '\n'
                        embed=discord.Embed(title='User(s) looking for a game:', description=msg)
                else:
                    if not os.path.isfile('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt'):
                        with open('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt', 'w') as f_o:
                            f_o.write(message.author.id + 'x')
                            embed=discord.Embed(title='You are now looking for game')
                    else:
                        with open('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt', 'r') as f_o:
                            file = f_o.readline()
                        if message.author.id in file:
                            file = file.replace(message.author.id + 'x', '', 1)
                            if file == '':
                                await bot.send_message(message.channel, 'here')
                                os.remove('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt')
                            else:
                                with open('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt', 'w') as f_o:
                                    f_o.write(file)
                            embed=discord.Embed(title='You are no longer looking for a game')
                        else:
                            file = file + message.author.id + 'x'
                            embed=discord.Embed(title='You are now looking for a game')
                            with open('/home/pi/pi_bot/lfg/' + message.channel.id + '.txt', 'w') as f_o:
                                f_o.write(file)
                embed.set_footer(text='Requested By: ' + message.author.name)
                await bot.send_message(message.channel, embed=embed)
            elif message.content.startswith('!pfp'):
                if len(message.mentions) == 0:
                    await bot.send_message(message.channel, message.author.mention + ' Make sure to mention the user.')
                else:
                    await bot.send_message(message.channel, message.mentions[0].avatar_url)
            elif message.content.startswith('!btc'):
                await bot.delete_message(message)
                loadingmsg = await bot.send_message(message.channel, 'Getting bitcoin rates...')
                btc = BtcConverter(force_decimal=True)
                embed = discord.Embed(title='Bitcoin -> Currency:', description='USD: $' + str(btc.get_latest_price('USD'))[0:8] + '\nCAD: $' + str(btc.get_latest_price('CAD'))[0:8] + '\nEUR: €' + str(btc.get_latest_price('EUR'))[0:8] + '\nAUD: $' + str(btc.get_latest_price('AUD'))[0:8])
                embed.add_field(name='Currency -> Bitcoin:', value='USD: ฿' + str(btc.convert_to_btc(1, 'USD'))[0:10] + '\nCAD: ฿' + str(btc.convert_to_btc(1, 'CAD'))[0:10] + '\nEUR: ฿' + str(btc.convert_to_btc(1, 'EUR'))[0:10] + '\nAUD: ฿' + str(btc.convert_to_btc(1, 'AUD'))[0:10], inline=False)
                embed.set_thumbnail(url="https://bitcoin.org/img/icons/opengraph.png")
                embed.set_footer(text='Requested by ' + message.author.name)
                await bot.send_message(message.channel, embed=embed)
                await bot.delete_message(loadingmsg)
                return
	    
	    
	    
	    #End Of Command Constants
            if purgecheck == 'placeholder':
                await bot.delete_message(message)
Пример #18
0
#Project 1.1 - Bitcoin Currency Converter

#Imports
from forex_python.bitcoin import BtcConverter
from datetime import datetime

#date_obj = datetime.datetime(2021,3,9,16,40,0,815417)
current_day = int(datetime.now().strftime('%d'))

if current_day > 1:
    day = current_day - 1

date_obj = datetime.now().strftime("%Y-%m-" + str(day) + " %H:%M:%S.%f")
#2018-05-18 19:39:36.815417
date = datetime.strptime(date_obj, '%Y-%m-%d %H:%M:%S.%f')
c = BtcConverter()

#Input
amount = int(input("Enter the amount for converter: "))
currency = input("Enter the currency: ").upper()
result = c.convert_to_btc(amount, currency)

#Output
print(result)
print("\nThe price of 1 bitcoin in " + str(date) + " in " + currency +
      " was " + str(c.get_previous_price(currency, date)))
Пример #19
0
class BitcoinBackend:
    UNCONFIRMED_ADDRESS_BALANCE = 0
    CONFIRMED_ADDRESS_BALANCE = 1
    UNDERPAID_ADDRESS_BALANCE = -1
    NO_HASH_ADDRESS_BALANCE = -2

    def __init__(self, public_key):
        self.public_key = public_key
        self.converter = BtcConverter()

    def get_address_output_value(self, address, outputs):
        for output in outputs:
            if address in output["addresses"]:
                return output["value"]

    def generate_new_address(self, index):
        """
        Generate new bitcoin address from a hd public master key based on a particlar index
        Address can be generated sequentially like in the case of electrum
        :param index: Index to use to generate address
        :return: Generated address
        """
        address = btc.pubkey_to_address(
            btc.bip32_descend(self.public_key, [0, index]))
        return address

    def convert_from_fiat(self, amount, currency="USD"):
        """
        Convert a fiat amount to bitcoin
        :param amount: Fiat amount to convert
        :param currency: Fiat currency
        :return: Rounded btc amount
        """
        res = self.converter.convert_to_btc(amount, currency)
        return round(res, 8)

    def convert_to_fiat(self, amount, currency):
        """
        Convert a btc amount to fiat amount
        :param amount: BTC amount to convert
        :param currency: Fiat currency to convert
        :return: Amount in specified currency
        """
        res = self.converter.convert_btc_to_cur(amount, currency)
        return round(res, 2)

    def confirm_address_payment(
        self,
        address,
        total_crypto_amount,
        confirmation_number=1,
        accept_confirmed_bal_without_hash_mins=20,
        tx_hash=None,
    ):
        """
        Confirm if a payment was made to a specified address.
        A payment that was already confirmed on the blockchain before running
        this tool can still be seen as paid by specifying a time
        frame such payment was confirmed and the time this tool is used on accept_confirmed_bal_without_hash_mins.
        :param address: Address to check for payment
        :param total_crypto_amount: Amount to check
        :param accept_confirmed_bal_without_hash_mins : You can accept already confirmed payment within this minute
         if there is no previous hash provided
        :param tx_hash: Transaction hash if any can be gotten from this method if payment is unconfirmed
        :param confirmation_number: Block chain confirmations below this are returned as unconfirmed
        :return: UNCONFIRMED_ADDRESS_BALANCE, traansaction hash | CONFIRMED_ADDRESS_BALANCE, payment_amount |
                    UNDERPAID_ADDRESS_BALANCE, remaining_crypto_amount |  NO_HASH_ADDRESS_BALANCE, None
        """
        if tx_hash:
            transaction = get_transaction_details(transaction_hash=tx_hash)
            value = self.get_address_output_value(address,
                                                  transaction["outputs"])
            if value is None:
                return self.NO_HASH_ADDRESS_BALANCE, None
            return self._check_balance_confirmations(
                transaction["confirmations"],
                transaction["hash"],
                confirmation_number,
                value,
                total_crypto_amount,
            )
        data = get_address_details(address)
        if data["unconfirmed_balance"] != 0 and data["unconfirmed_n_tx"] > 0:
            return (
                self.UNCONFIRMED_ADDRESS_BALANCE,
                extract_latest_transaction(
                    data["unconfirmed_txrefs"])["tx_hash"],
            )

        elif (data["unconfirmed_balance"] == 0
              and data["unconfirmed_n_tx"] == 0 and data["total_received"] > 0
              and data["n_tx"] > 0):

            transaction = extract_latest_transaction(data["txrefs"],
                                                     key="confirmed")
            if tx_hash == transaction["tx_hash"]:
                value = transaction["value"]
            elif tx_hash:

                transaction = get_transaction_details(transaction_hash=tx_hash)
                value = self.get_address_output_value(address,
                                                      transaction["outputs"])
                if value is None:
                    return self.NO_HASH_ADDRESS_BALANCE, None
            else:
                # There is a confirmed balance and we dont have any old  hash to track it
                transaction = confirm_transaction_date_without_previous_hash(
                    transaction,
                    accept_confirmed_bal_without_hash_mins,
                    key="confirmed")
                if transaction is None:
                    return self.NO_HASH_ADDRESS_BALANCE, None
                value = transaction["value"]

            return self._check_balance_confirmations(
                transaction["confirmations"],
                transaction["tx_hash"],
                confirmation_number,
                value,
                total_crypto_amount,
            )
        else:
            return NO_HASH_ADDRESS_BALANCE, None

    def _check_balance_confirmations(
        self,
        transaction_confirmations,
        tx_hash,
        confirmation_number,
        sent_value,
        total_crypto_amount,
    ):
        if transaction_confirmations < confirmation_number:
            return self.UNCONFIRMED_ADDRESS_BALANCE, tx_hash
        sent_btc_amount = convert_from_satoshi(sent_value)
        if sent_btc_amount < total_crypto_amount:
            remaining_crypto_amount = total_crypto_amount - sent_btc_amount
            return self.UNDERPAID_ADDRESS_BALANCE, remaining_crypto_amount
        return self.CONFIRMED_ADDRESS_BALANCE, sent_value
Пример #20
0
'''https://www.kurzy.cz/komodity/bitcoin-graf-vyvoje-ceny/'''
'''https://github.com/MicroPyramid/forex-python/blob/master/tests/test_bitcoin.py'''

from forex_python.bitcoin import (get_btc_symbol, convert_btc_to_cur_on,
                                  convert_to_btc_on, convert_btc_to_cur,
                                  convert_to_btc, get_latest_price,
                                  get_previous_price, get_previous_price_list,
                                  BtcConverter)

prevodnik = BtcConverter()

print(prevodnik.get_latest_price('USD'))
print(prevodnik.get_latest_price('CZK'))

kolik = int(input("Jaké množství Kč chcete vyměnit: "))
print(prevodnik.convert_to_btc(kolik, 'CZK'))
Пример #21
0
# jako druhé parametr zkratku zdrojové měny a jako třetí parametr množství požadovaných dolarů.
# Funkce vypočte, kolik jednotek zdrojové měny je potřeba zaplatit, aby to odpovídalo požadovanému množství cílové měny.
#

from forex_python.converter import CurrencyRates
initial_currency = input("What is your initial currency?")
prevodnik = CurrencyRates()
pozadovano_v_cilove_mene = int(
    input("How much money you need in the desired currency?"))

final_currency = prevodnik.convert('USD', initial_currency,
                                   pozadovano_v_cilove_mene)
print(int(final_currency))

# Zkus program upravit tak, aby zjistil požadovanou měnu od uživatele (pomocí funkce input()).
# Uvažuj, zkus např. pracovat s měnami EUR, GBP nebo DKK. Následně od uživatele získej i
# požadované množství cílové měny. Nezapomeň toho množství převést na typ int.
#
from forex_python.bitcoin import BtcConverter
b = BtcConverter()
initial_currency = input("What is your initial currency?")
pozadovano_v_cilove_mene = int(input("How many Bitcoin do you want?"))

final_currency = b.convert_to_btc(pozadovano_v_cilove_mene, initial_currency)
print(final_currency)

# Pokročilejší varianta
# Podívej se do dokumentace k modulu forex-python. Zjistíš, že umí pár dalších zajímavých věcí,
# například převod měny do Bitcoinu. Zkus pomocí modulu vytvořit program,
# který se zeptá uživatele na měnu a požadovaný počet Bitcoinů a vrátí mu množství měny,
# které by potřeboval, aby požadované množství Bitcoinů mohl koupit.