我在 VS Code 中工作,我被要求将 telegram bot 脚本从 python-telegram-bot 库更改为 aiogram。我已经通过“pip install aiogram”安装了它,但仍然收到类似 ModuleNotFoundError: No module named 'aiogram' 的错误,我不知道该怎么办。
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.types import ParseMode
from aiogram.utils import executor
import requests
TELEGRAM_BOT_TOKEN = 'XXXXXXXX'
COINGECKO_API_KEY = 'XXXXXXXX'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TELEGRAM_BOT_TOKEN)
dp = Dispatcher(bot)
# Function to get token price from CoinGecko
def get_token_price(token_id):
url = f'https://api.coingecko.com/api/v3/simple/price?ids={token_id}&vs_currencies=usd'
headers = {'Authorization': f'Bearer {COINGECKO_API_KEY}'}
response = requests.get(url, headers=headers)
data = response.json()
if 'error' in data:
logging.error(f'Error from CoinGecko API: {data["error"]}')
return None
try:
price = data[token_id]['usd']
return price
except KeyError:
logging.error(f'KeyError: Could not find price for token with ID {token_id}')
return None
# Command handlers
@dp.message_handler(commands=['btc'])
async def get_btc(message: types.Message):
price = get_token_price('bitcoin')
if price is not None:
await message.reply(f'Ціна Bitcoin: {price} USD')
else:
await message.reply('Не вдалося отримати ціну для Bitcoin')
@dp.message_handler(commands=['eth'])
async def get_eth(message: types.Message):
price = get_token_price('ethereum')
if price is not None:
await message.reply(f'Ціна Ethereum: {price} USD')
else:
await message.reply('Не вдалося отримати ціну для Ethereum')
@dp.message_handler(commands=['sfund'])
async def get_sfund(message: types.Message):
price = get_token_price('seedify-fund')
if price is not None:
await message.reply(f'Ціна Seedify: {price} USD')
else:
await message.reply('Не вдалося отримати ціну для Seedify Fund')
@dp.message_handler(commands=['cgpt'])
async def get_cgpt(message: types.Message):
price = get_token_price('chaingpt')
if price is not None:
await message.reply(f'Ціна ChainGPT: {price} USD')
else:
await message.reply('Не вдалося отримати ціну для ChainGPT')
@dp.message_handler(commands=['bnb'])
async def get_bnb(message: types.Message):
price = get_token_price('binancecoin')
if price is not None:
await message.reply(f'Ціна BNB: {price} USD')
else:
await message.reply('Не вдалося отримати ціну для Binance Coin (BNB)')
if __name__ == '__main__':
from aiogram import executor
executor.start_polling(dp, skip_updates=True)
尝试创建一个新项目(有时有帮助),但仍然出现同样的错误
我建议使用虚拟环境来避免这个问题。虚拟环境为您提供安全性或轻松安全地安装和卸载,此外,在激活后,由于其稳定性,它们将解决您的导入问题。
创建:
python3 -m venv venv
激活(Linux):
source venv/bin/activate
激活(W10 - Powershell):
venv\Scripts\activate
激活 venv 后,您只需安装所需的内容即可。
VS Code 通常会检测虚拟环境,它会询问您是否要在工作区中使用它:)
如果您想创建需求列表及其各自的版本,只需使用以下命令并将所有内容保存在需求 txt 文件中。
pip freeze > requirements.txt