【问题标题】:Python Telegram Price Bot with Website API带有网站 API 的 Python 电报价格机器人
【发布时间】:2021-05-24 11:45:27
【问题描述】:

我正在尝试为我的电报组制作一个非常简单的价格机器人。

令牌的数据取自 API。数据被正确提取,没有任何问题。但是,当我打开机器人并调用价格时,它只显示第一个价格,因为它会请求一次,之后不再循环。

有没有办法在机器人的函数中构建 API 调用,以便当我调用 /price 命令时,它会在那个时候从 API 中提取它?

我试过了:将 API 调用放在 bot 消息函数中,但它不能正常工作。

有没有办法让它工作?

在我的代码下面:

import os
import telebot
from requests_html import HTMLSession
import json
import urllib.request
from urllib.request import urlopen
import ssl

#Creating the bot with the attached API
API_KEY = ''
bot = telebot.TeleBot(API_KEY)

#Token price scraping

ssl._create_default_https_context = ssl._create_unverified_context
url = ''
data = urllib.request.urlopen(url).read()
jsonn = json.loads(data)
price_token = jsonn[-1][1]
print(price_token)

#Token price bot commands


@bot.message_handler(commands=['price'])
def pricetoken(message):
    bot.send_message(message.chat.id,price_token)


bot.polling(none_stop=True, timeout=200)

【问题讨论】:

  • 嗨。请删除 python-telegram-bot 标记,它用于不同的库;-)
  • 嗨,对不起,我现在删除了它!

标签: python json function py-telegram-bot-api


【解决方案1】:

嘿,试试替换 sn-ps,你使用的是一个单一的价格,它只获得一次,并且在价格命令发生时使用了多次

#Token price scraping

ssl._create_default_https_context = ssl._create_unverified_context
url = ''
data = urllib.request.urlopen(url).read()
jsonn = json.loads(data)
price_token = jsonn[-1][1]
print(price_token)

所以用类似函数的方法替换它,以便每次从 API 获取一个新值,如下所示。

def obtain_price():
   ssl._create_default_https_context = ssl._create_unverified_context
   url = ''
   data = urllib.request.urlopen(url).read()
   jsonn = json.loads(data)
   price_token = jsonn[-1][1]
   return price_token

这就是你所需要的!

你的新代码现在看起来像

import os
import telebot
from requests_html import HTMLSession
import json
import urllib.request
from urllib.request import urlopen
import ssl

#Creating the bot with the attached API
API_KEY = ''
bot = telebot.TeleBot(API_KEY)

def obtain_price():
   ssl._create_default_https_context = ssl._create_unverified_context
   url = ''
   data = urllib.request.urlopen(url).read()
   jsonn = json.loads(data)
   price_token = jsonn[-1][1]
   return price_token


@bot.message_handler(commands=['price'])
def pricetoken(message):
   price_token = obtain_price()
   bot.send_message(message.chat.id,price_token)


bot.polling(none_stop=True, timeout=200)

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2017-08-18
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多