Python:pyTelegramBotAPI命令不工作

2024-09-30 06:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pyTelegramBotAPI创建Telegrambot,出现以下错误:

所以功能是:当用户键入加密硬币名称时,例如BTCETHXRPbot必须显示价格和其他信息。。。但是当我在代码中有其他命令时,它就不起作用了,但是单独运行时效果很好,而其他命令运行得很好。我试过这个:

if "/" in tokename:
    pass
else:
    'do this'

但它不起作用。我也试过这个

if len(tokename) > 2:
    'do this'
else:
    pass

但没有结果

这是我的全部代码

import telebot
import time
import requests
import logging
from bs4 import BeautifulSoup
from telebot.types import Message
import json


bot_token = 'BOT_API_KEY'
nomics_api = 'NOMICS_API_KEY'

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)
bot = telebot.TeleBot(token=bot_token)

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

def convert_usd_to_crypto(coinname, dollar):
    try:
        response = json.loads(requests.get("https://api.nomics.com/v1/currencies/ticker?key=" + nomics_api + "&ids=" + coinname + "&convert=USD&per-page=100&page=1")._content)
        for r in response:
            price = r["price"]
            price = float(price)
            calculate = float(dollar) / float(price)
            calculated_result = '{0:,.3f}'.format(float(calculate))
            result = "🔸" + '{0:,.2f}'.format(float(dollar)) + "$" + coinname + " = " + \
            calculated_result + " " + coinname.strip()
            return result
    except:
        result = "ERROR!"
        return result

@bot.message_handler(commands=['to'])
def send_converted_crypto(message: Message):
    try:
        coin = message.text[3:7]
        coin = coin.upper()
        dollar = message.text[8:10000000000000000000000]
        final = convert_usd_to_crypto(coin, dollar)
        bot.reply_to(message, final)
    except:
        bot.reply_to(message, "ERROR!")


def cake_calculator(cake_raodenoba):
    try:
        cake_price_url = requests.get("https://bscscan.com/token/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82")
        soup = BeautifulSoup(cake_price_url.content, 'html.parser')
        price = soup.find(id='ContentPlaceHolder1_tr_valuepertoken')
        pricebox = price.find('span', class_='d-block').get_text()
        final_price = pricebox.strip()[:7].replace("$", "")
        final_price = float(final_price)
        cake_raodenoba = float(cake_raodenoba)
        totalstakedcake = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82&address=0x73feaa1ee314f8c655e354234017be2193c9e24e&tag=latest"
        response = requests.get(totalstakedcake)
        qeiqebi = response.json()
        cakepool = (int(qeiqebi["result"]) / 1000000000000000000)
        cakepool = int("{0:.0f}".format(cakepool))
        stakingunitpercent = '{:.15f}'.format(1 / cakepool * 100)
        totaldailyrewards = 288000
        stakingunitearns = float(stakingunitpercent) / 100 * totaldailyrewards
        ##########################################################################
        yourdailyreward = stakingunitearns * cake_raodenoba
        apy = yourdailyreward / cake_raodenoba * 100 * 365
        monthofcompounding = cake_raodenoba * (1 + apy/100/30)**(30*0.0865)
        twomonthofcompunding = cake_raodenoba * (1 + apy/100/30)**(60*0.0865)
        threemonthofcompunding = cake_raodenoba * (1 + apy/100/30)**(90*0.0865)
        ##########################################################################
        dailyrewardprice = float(final_price) * float(yourdailyreward)
        monthofcompoundingprice = float(final_price) * float(monthofcompounding) 
        twomonthofcompundingprice = float(final_price) * float(twomonthofcompunding)
        threemonthofcompundingprice = float(final_price) * float(threemonthofcompunding)
        ##########################################################################
        inputed_cake = float(final_price) * float(cake_raodenoba)
        full_cake = "🥞 " + '{0:,.2f}'.format(float(cake_raodenoba)) + " CAKE = $" + '{0:,.2f}'.format(float(inputed_cake)) + "\n" + "▶️ 1 day: " + '{0:,.2f}'.format(float(yourdailyreward)) + " CAKE"  + " ($" + '{0:,.2f}'.format(float(dailyrewardprice)) + ")" +  "\n" + "▶️ APY: " + '{0:,.2f}'.format(float(apy)) + "%" + "\n" + "==========🔸" + "1 CAKE = $" + '{0:,.2f}'.format(float(final_price)) + "🔸==========" + "\n" + "▶️ 1 month, daily reinvest: " + '{0:,.2f}'.format(float(monthofcompounding)) + " CAKE"   + " ($" + '{0:,.2f}'.format(float(monthofcompoundingprice)) + ")" +   "\n" + "▶️ 2 month, daily reinvest: " + '{0:,.2f}'.format(float(twomonthofcompunding)) + " CAKE"   + " ($" + '{0:,.2f}'.format(float(twomonthofcompundingprice)) + ")" +  "\n" + "▶️ 3 month, daily reinvest: " + '{0:,.2f}'.format(float(threemonthofcompunding)) + " CAKE" + " ($" + '{0:,.2f}'.format(float(threemonthofcompundingprice)) + ")"
        return full_cake
    except:
        return "USE ONLY NUMBERS : /cake 100"


@bot.message_handler(commands=['cake'])
def send_cakecalculator(message: Message):
    cake_raodenoba = message.text[5:]
    bot.reply_to(message, cake_calculator(cake_raodenoba))

def cake_calculator_usd(cake_usd_raodenoba):
    try:
        cake_price_url = requests.get("https://bscscan.com/token/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82")
        soup = BeautifulSoup(cake_price_url.content, 'html.parser')
        price = soup.find(id='ContentPlaceHolder1_tr_valuepertoken')
        pricebox = price.find('span', class_='d-block').get_text()
        final_price = pricebox.strip()[:7].replace("$", "")
        final_price = float(final_price)
        ##########################################################################
        #cake_raodenoba = float(input_user) / float(final_price)
        #number of bitcoins = 'value in USD' / 'exchange rate'
        cake_raodenoba = float(cake_usd_raodenoba) / float(final_price)
        ##########################################################################
        totalstakedcake = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82&address=0x73feaa1ee314f8c655e354234017be2193c9e24e&tag=latest"
        response = requests.get(totalstakedcake)
        qeiqebi = response.json()
        cakepool = (int(qeiqebi["result"]) / 1000000000000000000)
        cakepool = int("{0:.0f}".format(cakepool))
        stakingunitpercent = '{:.15f}'.format(1 / cakepool * 100)
        totaldailyrewards = 288000
        stakingunitearns = float(stakingunitpercent) / 100 * totaldailyrewards
        ##########################################################################
        yourdailyreward = stakingunitearns * cake_raodenoba
        apy = yourdailyreward / cake_raodenoba * 100 * 365
        monthofcompounding = cake_raodenoba * (1 + apy/100/30)**(30*0.0865)
        twomonthofcompunding = cake_raodenoba * (1 + apy/100/30)**(60*0.0865)
        threemonthofcompunding = cake_raodenoba * (1 + apy/100/30)**(90*0.0865)
        ##########################################################################
        dailyrewardprice = float(final_price) * float(yourdailyreward)
        monthofcompoundingprice = float(final_price) * float(monthofcompounding) 
        twomonthofcompundingprice = float(final_price) * float(twomonthofcompunding)
        threemonthofcompundingprice = float(final_price) * float(threemonthofcompunding)
        ##########################################################################
        full_cake = "🔸 $" + '{0:,.2f}'.format(float(cake_usd_raodenoba)) + " = " + '{0:,.2f}'.format(float(cake_raodenoba)) + " CAKE 🥞 " + "\n" + "▶️ 1 day: " + '{0:,.2f}'.format(float(yourdailyreward)) + " CAKE"  + " ($" + '{0:,.2f}'.format(float(dailyrewardprice)) + ")" +  "\n" + "▶️ APY: " + '{0:,.2f}'.format(float(apy)) + "%" + "\n" + "==========🔸" + "1 CAKE = $" + '{0:,.2f}'.format(float(final_price)) + "🔸==========" + "\n" + "▶️ 1 month, daily reinvest: " + '{0:,.2f}'.format(float(monthofcompounding)) + " CAKE"   + " ($" + '{0:,.2f}'.format(float(monthofcompoundingprice)) + ")" +   "\n" + "▶️ 2 month, daily reinvest: " + '{0:,.2f}'.format(float(twomonthofcompunding)) + " CAKE"   + " ($" + '{0:,.2f}'.format(float(twomonthofcompundingprice)) + ")" +  "\n" + "▶️ 3 month, daily reinvest: " + '{0:,.2f}'.format(float(threemonthofcompunding)) + " CAKE" + " ($" + '{0:,.2f}'.format(float(threemonthofcompundingprice)) + ")"
        return full_cake
    except:
        return "USE ONLY NUMBERS : /usdtocake 100"

@bot.message_handler(commands=['usdtocake'])
def send_cakecalculator_usd(message: Message):
    try:
        cake_usd_raodenoba = message.text[10:]
        bot.reply_to(message, cake_calculator_usd(cake_usd_raodenoba))
    except:
        pass


######THIS NOT WORKING######
@bot.message_handler(func=lambda message: True)
def send_tokenprice(message: Message):
    tokename = (message.text).upper()
    if len(tokename) > 2:
        response = json.loads(requests.get("https://api.nomics.com/v1/currencies/ticker?key=" + nomics_api + "&ids=" + tokename + "&convert=USD&per-page=100&page=1")._content)
        name = response[0]['name']
        symbol = response[0]['symbol']
        price = response[0]['price']
        price = '{0:,.3f}'.format(float(price))
        rank = response[0]['rank']
        market_cap = response[0]['market_cap']
        market_cap = '{0:,.2f}'.format(float(market_cap))
        volume = response[0]['1d']['volume']
        volume = '{0:,.2f}'.format(float(volume))
        full_info = "*" + str(name) + " (" + str(symbol) + ")" + "*" + "\n" + \
                    "*Price: $*" + str(price) + "\n" + \
                    "*Rank: *" + str(rank) + "\n" + \
                    "*MCap: $*" + str(market_cap) + "\n" + \
                    "*Volume: $*" + str(volume) + "\n"
        bot.reply_to(message, full_info, parse_mode='Markdown')
    else:
        pass

while True:
    try:
        bot.polling()
        break
    except Exception:
        time.sleep(30)```
 

Tags: toapiformatmessagegetresponsebotfloat

热门问题