-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
208 lines (168 loc) · 8.01 KB
/
bot.py
File metadata and controls
208 lines (168 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import telebot
from telebot import types
import requests
import time
from config import TOKEN, EXCHANGERATE_API_KEY
bot = telebot.TeleBot(TOKEN)
last_crypto_rates = None
last_fiat_rates = None
last_rates_message_id = None
last_help_message_id = None
last_start_message_id = None
def get_crypto_rates():
try:
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
'ids': 'bitcoin,ethereum,litecoin,solana,tether',
'vs_currencies': 'usd'
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error fetching crypto rates: {e}")
return None
def get_usd_rub_rate():
try:
url = f'https://v6.exchangerate-api.com/v6/{EXCHANGERATE_API_KEY}/pair/USD/RUB'
r = requests.get(url)
data = r.json()
if data.get('result') == 'success':
exchange_rate = data['conversion_rate']
return float(exchange_rate)
else:
print(f"Error in API response: {data}")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching USD to RUB rate: {e}")
return None
except KeyError as e:
print(f"Error: Key {e} not found in API response.")
print("Response:", data)
return None
def get_coin_metrics(coin_id):
url = f"https://api.coingecko.com/api/v3/coins/{coin_id}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
'volume': data['market_data']['total_volume']['usd'],
'liquidity': data['liquidity_score'],
'market_cap': data['market_data']['market_cap']['usd']
}
else:
return None
@bot.message_handler(commands=['start'])
def send_welcome(message):
global last_start_message_id
if last_start_message_id:
try:
bot.delete_message(message.chat.id, last_start_message_id)
print(f"Удалено предыдущее сообщение с ID: {last_start_message_id}")
except Exception as e:
print(f"Ошибка при удалении сообщения: {e}")
reply = 'Привет! Я помогу отслеживать курсы валют и криптовалют, а также быстро конвертировать вашу собственную сумму. Используй команду /rate для получения актуальных курсов.'
markup = types.InlineKeyboardMarkup()
rate_button = types.InlineKeyboardButton("Узнать курс", callback_data="rate")
markup.add(rate_button)
sent_message = bot.send_photo(message.chat.id, photo=open('mike.jpg', 'rb'), caption=reply, reply_markup=markup)
last_start_message_id = sent_message.message_id
print(f"Отправлено новое сообщение с ID: {last_start_message_id}")
@bot.message_handler(commands=['help'])
def send_help(message):
global last_help_message_id
if last_help_message_id:
try:
bot.delete_message(message.chat.id, last_help_message_id)
except Exception as e:
print(f"Ошибка при удалении сообщения: {e}")
commands = """
📜 Доступные команды:
/start - Начать работу с ботом
/help - Список команд
/rate - Курсы валют и криптовалют в USD/RUB
"""
sent_message = bot.reply_to(message, commands)
last_help_message_id = sent_message.message_id
@bot.callback_query_handler(func=lambda call: call.data == "rate")
def handle_rate_callback(call):
send_rates(call.message)
@bot.message_handler(commands=['rate'])
def send_rates(message):
global last_crypto_rates, last_fiat_rates, last_rates_message_id
if last_rates_message_id:
try:
bot.delete_message(message.chat.id, last_rates_message_id)
except Exception as e:
print(f"Error deleting message: {e}")
crypto_rates = get_crypto_rates()
usd_to_rub = get_usd_rub_rate()
if not crypto_rates or not usd_to_rub:
bot.reply_to(message, "🚫 Error fetching data. Please try again later.")
return
last_crypto_rates = crypto_rates
last_fiat_rates = usd_to_rub
reply = "📊 Current Rates:\n\n"
reply += f"💵 1 USD = {usd_to_rub:.2f} RUB\n"
reply += f"💲 1 USDT = {crypto_rates['tether']['usd'] * usd_to_rub:.2f} RUB\n"
reply += f"\n💰 1 BTC = {crypto_rates['bitcoin']['usd']:.2f} USDT\n"
reply += f"🔷 1 ETH = {crypto_rates['ethereum']['usd']:.2f} USDT\n"
reply += f"🔶 1 LTC = {crypto_rates['litecoin']['usd']:.2f} USDT\n"
reply += f"🌀 1 SOL = {crypto_rates['solana']['usd']:.2f} USDT\n"
reply += "\nConversion to RUB:\n"
reply += f"💰 1 BTC = {crypto_rates['bitcoin']['usd'] * usd_to_rub:.2f} RUB\n"
reply += f"🔷 1 ETH = {crypto_rates['ethereum']['usd'] * usd_to_rub:.2f} RUB\n"
reply += f"🔶 1 LTC = {crypto_rates['litecoin']['usd'] * usd_to_rub:.2f} RUB\n"
reply += f"🌀 1 SOL = {crypto_rates['solana']['usd'] * usd_to_rub:.2f} RUB\n"
markup = types.InlineKeyboardMarkup()
convert_button = types.InlineKeyboardButton("Convert Your Amount 👇", callback_data="convert")
markup.add(convert_button)
sent_message = bot.send_video(message.chat.id, video=open('token.mp4', 'rb'), caption=reply, reply_markup=markup)
last_rates_message_id = sent_message.message_id
@bot.callback_query_handler(func=lambda call: call.data == "convert")
def handle_convert_callback(call):
markup = types.InlineKeyboardMarkup()
usdt_button = types.InlineKeyboardButton("USDT", callback_data="convert_usdt")
btc_button = types.InlineKeyboardButton("BTC", callback_data="convert_btc")
eth_button = types.InlineKeyboardButton("ETH", callback_data="convert_eth")
ltc_button = types.InlineKeyboardButton("LTC", callback_data="convert_ltc")
sol_button = types.InlineKeyboardButton("SOL", callback_data="convert_sol")
markup.add(usdt_button, btc_button, eth_button, ltc_button, sol_button)
bot.send_message(call.message.chat.id, "Выберите валюту для конвертации:", reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.startswith("convert_"))
def handle_currency_selection(call):
bot.delete_message(call.message.chat.id, call.message.message_id)
currency = call.data.split("_")[1]
bot.send_message(call.message.chat.id, f"Введите сумму в {currency.upper()} для конвертации в RUB:")
bot.register_next_step_handler(call.message, lambda message: convert_amount(message, currency))
def convert_amount(message, currency):
currency_mapping = {
'usdt': 'tether',
'btc': 'bitcoin',
'eth': 'ethereum',
'ltc': 'litecoin',
'sol': 'solana'
}
global last_crypto_rates, last_fiat_rates
try:
amount = float(message.text)
except ValueError:
bot.reply_to(message, "🚫 Неверный формат. Пожалуйста, введите число.")
return
crypto_rates = last_crypto_rates
usd_to_rub = last_fiat_rates
if not crypto_rates or not usd_to_rub:
bot.reply_to(message, "🚫 Ошибка при получении данных. Пожалуйста, попробуйте позже.")
return
full_currency_name = currency_mapping.get(currency)
if not full_currency_name:
bot.reply_to(message, "🚫 Неизвестная валюта.")
return
crypto_to_usd = crypto_rates[full_currency_name]['usd']
converted_amount = amount * crypto_to_usd * usd_to_rub
bot.reply_to(message, f"💱 {amount} {currency.upper()} = {converted_amount:.2f} RUB")
@bot.message_handler(func=lambda message: True)
def handle_unknown(message):
bot.reply_to(message, "🚫 Неизвестная команда. Используйте /help для списка команд.")
bot.polling()