Skip to content

Instantly share code, notes, and snippets.

@Forevka
Last active May 16, 2021 10:44
Show Gist options
  • Save Forevka/b089ddc0aa1025b4e73e871724fc4502 to your computer and use it in GitHub Desktop.
Save Forevka/b089ddc0aa1025b4e73e871724fc4502 to your computer and use it in GitHub Desktop.
import sys, traceback, time, telebot, random, dbworker,requests
import wget,os
import lxml.html as lhtml
from telebot import types
from telegram.ext import Updater
import datetime
import time
import cherrypy
from telebot.types import LabeledPrice
#python -mwebbrowser "http://localhost:8000/cgi-bin/get_id.py?id=3&day=49"
token="592518282:AAEONWRnzhHCmUgDM2mBkNVoZHJrtGdvecM"#"520067503:AAGxM_atlDYN9FYOmgsJ7Wjid4K27OIEIGE"
provider_token = "361519591:TEST:137668481216a8c70d7e6cd6c16a3a0f"
WEBHOOK_HOST = '104.196.11.194'
WEBHOOK_PORT = 443 # 443, 80, 88 или 8443 (порт должен быть открыт!)
WEBHOOK_LISTEN = '104.196.11.194' # На некоторых серверах придется указывать такой же IP, что и выше
WEBHOOK_SSL_CERT = 'webhook_cert.pem' # Путь к сертификату
WEBHOOK_SSL_PRIV = 'webhook_pkey.pem' # Путь к приватному ключу
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (token)
bot = telebot.TeleBot(token)
u = Updater(token)
j = u.job_queue
j.start()
to_channel = "-1001335131674"
class WebhookServer(object):
@cherrypy.expose
def index(self):
if 'content-length' in cherrypy.request.headers and \
'content-type' in cherrypy.request.headers and \
cherrypy.request.headers['content-type'] == 'application/json':
length = int(cherrypy.request.headers['content-length'])
json_string = cherrypy.request.body.read(length).decode("utf-8")
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
raise cherrypy.HTTPError(403)
@bot.message_handler(func=lambda message: dbworker.get_state(message.chat.id) == 1)
def get_money_amount(message):
print("get money")
if number_or_not(message.text):
if int(message.text)>=50:
prices = [LabeledPrice(label='Пополнение счета на {} грн'.format(message.text), amount=int(message.text+"00"))]
bot.send_invoice(message.chat.id, title='Пополнение счета на {} грн'.format(message.text),
description='{} грн чтобы делать ставки на аукционе'.format(message.text),
provider_token=provider_token,
currency='uah',
photo_url='http://paint-net.ru/img4/img44/44023.png',
photo_height=414, # !=0/None or picture won't be shown
photo_width=312,
photo_size=512,
is_flexible=False, # True If you need to set up Shipping Fee
prices=prices,
start_parameter='time-machine-example',
invoice_payload='{}'.format(message.text))
dbworker.set_state(message.chat.id, 0)
else:
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="❌ Отмена", callback_data="account_bill="+str(message.message_id)))
bot.send_message(message.chat.id, '👌 Сумма должна быть не меньше чем 50 грн', reply_markup=keyboard_)
dbworker.set_state(message.chat.id, 1)
#bot.register_next_step_handler(message, get_money_amount)
else:
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="❌ Отмена", callback_data="account_bill="+str(message.message_id)))
bot.send_message(message.chat.id, '👌 Мы принимаем только целые числа.\nНапример 100 или 123, попробуй отправить еще раз', reply_markup=keyboard_)
dbworker.set_state(message.chat.id, 1)
#bot.register_next_step_handler(message, get_money_amount)
@bot.shipping_query_handler(func=lambda query: True)
def shipping(shipping_query):
print(shipping_query)
bot.answer_shipping_query(shipping_query.id, ok=True, shipping_options=shipping_options,
error_message='🛑 Похоже произошел какойто сбой, попробуй позже')
@bot.pre_checkout_query_handler(func=lambda query: True)
def checkout(pre_checkout_query):
bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True,
error_message="👽 Инопланетяни попробовали украсть твой CVV код, но мы успешно защитили его.\nПопробуй позже")
@bot.message_handler(content_types=['successful_payment'])
def got_payment(message):
print(message)
print(message.successful_payment.invoice_payload)
amount = message.successful_payment.invoice_payload
user_money = dbworker.get_user(message.from_user.id)[2];
if user_money == None:
user_money = 0;
dbworker.set_user_money(message.from_user.id, int(user_money)+int(amount));
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="💰 Операции со счетом", callback_data="account_bill="+str(message.message_id)));
keyboard_.row(types.InlineKeyboardButton(text="⬅️ В меню", callback_data="menu="+str(message.message_id)));
dbworker.set_state(message.chat.id, 0)
bot.send_message(message.chat.id,"👍 Спасибо за покупку!\nНа ваш счет в течении пары минут будет зачислено {0} {1}.".format(message.successful_payment.total_amount / 100, message.successful_payment.currency),
parse_mode='Markdown', reply_markup=keyboard_)
@bot.message_handler(func=lambda message: True)
def check_text(message):
if message.text.find("/new")>=0 and message.from_user.id == 383492784:
arg = message.text.replace("\n","").split("|");
if len(arg)<=5:
bot.send_message(message.chat.id, "1 - описание\n2 - ссылка на фото\n3 - начальная цена\n4 - цена выкуп\n5 - время до конца в секундах")
else:
description = '<a href="'+arg[2]+'">Фото</a>\n\n<b>📜 Описание:</b>'+arg[1]+"\n\n<b>💵 Цена:</b> "+arg[3]+"\n<b>💎 Цена выкупа:</b> "+arg[4]+"\n<b>⏰ Время на проведение:</b> "+str(datetime.timedelta(seconds=int(arg[5])));
idd = dbworker.new_auction(arg[1], arg[2], arg[3], arg[4], arg[5])
keyboard_ = types.InlineKeyboardMarkup()
prices = ["1", "2", "5", "10"]
for i in range(0, len(prices), 2):
keyboard_.row(types.InlineKeyboardButton(text="🔥 Повысить на "+prices[i], callback_data="increment_price="+str(prices[i])+"="+str(idd)), types.InlineKeyboardButton(text="🔥 Повысить на "+prices[i+1], callback_data="increment_price="+str(prices[i+1])+"="+str(idd)));
#keyboard_.row(types.InlineKeyboardButton(text="Выкупить!", callback_data="fast_buy="+str(idd)));
print("MESSAGE ID "+str(message.message_id))
msg = bot.send_message(to_channel, description, reply_markup=keyboard_, parse_mode="HTML")
print(msg.message_id)
dbworker.set_message_id(idd, msg.message_id)
keyboard_.row(types.InlineKeyboardButton(text="💎 Выкупить!", callback_data="fast_buy="+str(idd)+"="+str(msg.message_id)+"="+str(arg[4])));
bot.edit_message_text(message_id=msg.message_id, chat_id=to_channel, text=description, reply_markup=keyboard_, parse_mode="HTML")
elif message.text.find("/start")>=0 or message.text.find("🏠 Главное меню")>=0:
dbworker.set_username(message.chat.id, message.from_user.username)
dbworker.set_state(message.chat.id, 0)
body = "Привет!\nЯ твой личный кабинет 🎫 канала @buy_auc\nУ меня ты можешь пополнить свой счет 💰, что-бы участововать в аукционе.\nТакже здесь ты можешь подать заявку на продажу своей вещи в аукционной системе"
#dbworker.set_username(message.chat.id, message.from_user.username)
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="💰 Операции со счетом", callback_data="account_bill="+str(message.message_id)));
keyboard_.row(types.InlineKeyboardButton(text="📝 Мои ставки", callback_data="my_action="+str(message.message_id)+"=0"));
keyboard_.row(types.InlineKeyboardButton(text="📲 Уведомления", callback_data="notification="+str(message.message_id)+"=0"));
#keyboard_.row(types.InlineKeyboardButton(text="📜 Подать обьявление", callback_data="create_auction="+str(message.message_id)));
keyboard_.row(types.InlineKeyboardButton(text="⁉️ Правила и остальная иформация ", callback_data="more_info="+str(message.message_id)));
bot.send_message(chat_id=message.chat.id, text=body, reply_markup=keyboard_)
def number_or_not(num):
try:
num = int(num);
except:
return False;
return True;
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
#print(call)
user_username = call.from_user.username;
user_id = call.from_user.id;
print(user_username, user_id)
#dbworker.set_username(int(user_id),user_username)
if call.message:
if call.data.find("increment_price=")>=0:
user_info = dbworker.get_user(int(user_id))
arg = call.data.split("=");
if user_info[2]==None or user_info[2]<int(arg[1]):
bot.answer_callback_query(callback_query_id=call.id,text="Недостаточно денег на счету!Попробуйте пополнить у нашего бота", show_alert=True);
else:
bot.answer_callback_query(callback_query_id=call.id,text="Вы успешно подняли ставку на лот.")
dbworker.set_user_money(user_id, user_info[2]-int(arg[1]))
dbworker.update_auction_price(int(arg[2]), arg[1])
auc = dbworker.get_auction_id(int(arg[2]))
msg_id = dbworker.get_message_id(int(arg[2]))
description = '<a href="'+str(auc[3])+'">Фото</a>\n\n<b>📜 Описание:</b>'+str(auc[2])+"\n\n<b>💵 Цена:</b> "+str(auc[4])+"\n<b>💎 Цена выкупа:</b> "+str(auc[5])+"\n<b>⏰ Время на проведение:</b> "+str(datetime.timedelta(seconds=int(auc[6])));
keyboard_ = types.InlineKeyboardMarkup()
now = datetime.datetime.strptime(str(datetime.datetime.now()).split(".")[0], "%Y-%m-%d %H:%M:%S")
sql_command='Время '+str(now)+' Поднял на '+arg[1]+' грн лот №_'+str(auc[0])+'#'
print(sql_command)
dbworker.user_add_action(user_id, sql_command)
dbworker.set_who_buy(int(arg[2]), user_id)
prices = ["1", "2", "5", "10"]
#print("MESSAGE ID "+str(arg[3]))
for i in range(0, len(prices), 2):
keyboard_.row(types.InlineKeyboardButton(text="🔥 Повысить на "+prices[i], callback_data="increment_price="+str(prices[i])+"="+str(arg[2])+"="+str(msg_id)), types.InlineKeyboardButton(text="🔥 Повысить на "+prices[i+1], callback_data="increment_price="+str(prices[i+1])+"="+str(arg[2])+"="+str(msg_id)));
keyboard_.row(types.InlineKeyboardButton(text="💎 Выкупить!", callback_data="fast_buy="+str(arg[2])+"="+str(msg_id)+"="+str(auc[5])));
bot.edit_message_text(message_id=msg_id, chat_id=call.message.chat.id, text=description, reply_markup=keyboard_, parse_mode="HTML")
elif call.data.find("more_info=")>=0:
arg = call.data.split("=");
msg_id = arg[1]
reply = "Это первый бот-канал аукцион в телеграмме!\nМы стараемся продавать только ценные и интересные вещи, вы всегда сможете найти то что вам нужно!\n\nНемного правил:\nМы не возвращаем деньги которые лежат у вас на счету.\nЗачисление происходит в течении 1-30 минут, если не сразу зачислило попробуйте подождать.\nЦены указаны в гривнах, и только в них.\nОрганизаторы имеют право снять лот с продажи без возврата средств.\nВам должно быть больше 18 лет.\n\nУдачных торгов!"
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="⬅️ К кабинету", callback_data="menu="+str(msg_id)))
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, reply_markup=keyboard_)
elif call.data.find("notification=")>=0:
arg = call.data.split("=");
msg_id = arg[1];
max_id = arg[2]
reply = "<b>Здесь выводятся ваши выигрыши и другие уведомления</b>"
btn_prev = None;
btn_next = None;
auctions = dbworker.get_all_inactive_auctions();
#print(auctions)
keyboard_ = types.InlineKeyboardMarkup()
win_auctions = [];
for i in auctions:
if int(i[8])==int(user_id):
#auc = auctions[i];
win_auctions.append(i);
print(len(win_auctions))
ct = len(win_auctions)
"""if ct>0:
ct-=1
else:
ct = 0;"""
reply+="\n\n<b>Всего: </b>"+str(ct)
if len(win_auctions)>0:
for i in range(int(max_id),int(max_id)+5,1):
try:
auc = win_auctions[i];
keyboard_.row(types.InlineKeyboardButton(text="#️⃣ "+str(i+1)+" ID "+str(auc[0])+" "+str(auc[2][:15])+"...", callback_data="user_win_auc="+str(msg_id)+"="+str(auc[0])));
except:
break;
else:
reply+="\n\n<b>Вы не выиграли и не выкупили ниодного лота</b>"
if int(max_id)!=0:
btn_prev = types.InlineKeyboardButton(text="🔙 Предидущие", callback_data="notification="+str(msg_id)+"="+str(int(max_id)-5));
if int(max_id)<len(win_auctions)-6:
btn_next = types.InlineKeyboardButton(text="Следующие 🔜", callback_data="notification="+str(msg_id)+"="+str(int(max_id)+5));
if btn_prev!=None and btn_next!=None:
keyboard_.row(btn_prev, btn_next)
elif btn_prev!=None:
keyboard_.row(btn_prev)
elif btn_next!=None:
keyboard_.row(btn_next)
keyboard_.row(types.InlineKeyboardButton(text="⬅️ К кабинету", callback_data="menu="+str(msg_id)))
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, reply_markup=keyboard_, parse_mode="HTML")
elif call.data.find("user_win_auc=")>=0:
arg = call.data.split("=");
msg_id = arg[1];
auc = arg[2];
auc = dbworker.get_auction_id(int(arg[2]));
reply = '<a href="'+str(auc[3])+'">Фото</a>\n\n<b>📜 Описание:</b>'+str(auc[2])+"\n\n<b>💵 Цена:</b> "+str(auc[4])+"\n<b>💎 Цена выкупа:</b> "+str(auc[5])+"\n<b>⏰ Время на проведение:</b> "+str(datetime.timedelta(seconds=int(auc[6])));
reply+= "\n\n<code>Если с вами еще не связался продавец то пишите @forevka</code>"
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="⬅️ Назад", callback_data="notification="+str(msg_id)+"=0"))
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, parse_mode="HTML", reply_markup=keyboard_)
elif call.data.find("fast_buy=")>=0:
user_info = dbworker.get_user(int(user_id))
arg = call.data.split("=");
if user_info[2]==None or user_info[2]<int(arg[3]):
bot.answer_callback_query(callback_query_id=call.id,text="Недостаточно денег на счету!Попробуйте пополнить у нашего бота", show_alert=True);
else:
bot.answer_callback_query(callback_query_id=call.id,text="Поздравляем, вы выкупили этот лот!\nОжидайте, c вами свяжется продавец")
dbworker.set_user_money(user_id, user_info[2]-int(arg[3]))
print(arg)
auc = dbworker.get_auction_id(int(arg[1]))
now = datetime.datetime.strptime(str(datetime.datetime.now()).split(".")[0], "%Y-%m-%d %H:%M:%S")
sql_command='Время '+str(now)+' Выкупил за '+arg[3]+' грн лот №_'+str(auc[0])+'#'
print(sql_command)
dbworker.user_add_action(user_id, sql_command)
dbworker.set_who_buy(int(arg[1]), user_id);
dbworker.end_auction(int(arg[1]));
description = '<a href="'+str(auc[3])+'">Фото</a>\n\n<b>📜 Описание:</b>'+str(auc[2])+"\n\n<b>💵 Цена:</b> "+str(auc[4])+"\n<b>💎 Цена выкупа:</b> "+str(auc[5])+"\n\n<b>🎯 Выкуплен!</b>"
bot.edit_message_text(message_id=arg[2], chat_id=call.message.chat.id, text=description, parse_mode="HTML")
elif call.data.find("menu=")>=0:
arg = call.data.split("=");
msg_id = arg[1];
body = "Привет!\nЯ твой личный кабинет 🎫 канала @buy_auc\nУ меня ты можешь пополнить свой счет 💰, что-бы участововать в аукционе.\nТакже здесь ты можешь подать заявку на продажу своей вещи в аукционной системе"
#dbworker.set_username(message.chat.id, message.from_user.username)
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="💰 Операции со счетом", callback_data="account_bill="+str(msg_id)));
keyboard_.row(types.InlineKeyboardButton(text="📝 Мои ставки", callback_data="my_action="+str(msg_id)+"=0"));
keyboard_.row(types.InlineKeyboardButton(text="📲 Уведомления", callback_data="notification="+str(msg_id)+"=0"));
keyboard_.row(types.InlineKeyboardButton(text="📜 Подать обьявление", callback_data="create_auction="+str(msg_id)));
keyboard_.row(types.InlineKeyboardButton(text="⁉️ Узнать больше", callback_data="more_info="+str(msg_id)));
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=body, reply_markup=keyboard_)
#bot.delete_message(chat_id=call.message.chat.id, message_id=int(arg[1])+1)
#main_menu(call.message)
elif call.data.find("my_action=")>=0:
arg = call.data.split("=");
msg_id = arg[1];
max_id = arg[2];
if int(max_id)<0:
max_id = 0;
user_info = dbworker.get_user(call.message.chat.id)
if user_info[4]!=None:
actions = user_info[4].replace("_"," ").split("#")
else:
actions = [];
print("actions",len(actions))
print("max_id",max_id)
ct = len(actions)
if ct>0:
ct-=1
else:
ct = 0;
reply="<b>Ваши ставки</b>\nВсего: "+str(ct)+"\n\n";
keyboard_ = types.InlineKeyboardMarkup()
btn_end = None;
#btn_refresh = types.InlineKeyboardButton(text="🔄 Обновить", callback_data="my_action="+str(msg_id)+"="+str(int(max_id)))
lot_id = 0;
if user_info[4]==None or user_info[4]=="":
reply+="Нету ставок";
else:
for i in range(int(max_id),int(max_id)+5,1):
print(i)
#lot_id = actions.split("_");
try:
lot_id = user_info[4].split("#")[i].split("_");
print(lot_id)
if i<len(actions)-1:
keyboard_.row(types.InlineKeyboardButton(text="#️⃣ "+str(i+1)+" "+actions[i], callback_data="bet="+str(msg_id)+"="+str(lot_id[1])+"="+str(i)));
except:
break;
if len(actions)>5:
btn_end = types.InlineKeyboardButton(text="В конец 🔜", callback_data="my_action="+str(msg_id)+"="+str(len(actions)-5))
#reply+=i+"\n"
btn_prev = None;
btn_next = None;
if int(max_id)!=0:
btn_prev = types.InlineKeyboardButton(text="🔙 Предидущие", callback_data="my_action="+str(msg_id)+"="+str(int(max_id)-5));
if int(max_id)<len(actions)-6:
btn_next = types.InlineKeyboardButton(text="Следующие 🔜", callback_data="my_action="+str(msg_id)+"="+str(int(max_id)+5));
if btn_prev!=None and btn_next!=None:
keyboard_.row(btn_prev, btn_next)
elif btn_prev!=None:
keyboard_.row(btn_prev)
elif btn_next!=None:
keyboard_.row(btn_next)
if btn_end!=None:
keyboard_.row(types.InlineKeyboardButton(text="⬅️ К кабинету", callback_data="menu="+str(msg_id)), btn_end);
else:
keyboard_.row(types.InlineKeyboardButton(text="⬅️ К кабинету", callback_data="menu="+str(msg_id)))
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, parse_mode="HTML",reply_markup=keyboard_)
elif call.data.find("bet=")>=0:
arg = call.data.split("=");
print(arg)
msg_id = arg[1];
auc_id = arg[2];
on_user_position = arg[3];
user_info = dbworker.get_user(call.message.chat.id)
actions = user_info[4].replace("_"," ").split("#")
user_action = actions[int(on_user_position)]
auc = dbworker.get_auction_id(int(arg[2]));
reply = '<a href="'+str(auc[3])+'">Фото</a>\n\n<b>📜 Описание:</b>'+str(auc[2])+"\n\n<b>💵 Цена:</b> "+str(auc[4])+"\n<b>💎 Цена выкупа:</b> "+str(auc[5])+"\n<b>⏰ Время на проведение:</b> "+str(datetime.timedelta(seconds=int(auc[6])));
reply+="\n\n"+user_action
if int(auc[7])==1:
reply+="\n\n<b>Поставить новую ставку вы можете по ссылке</b> t.me/buy_auc/"+str(auc[1]);
else:
reply+="\n\n<b>Данный лот был завершен или выкуплен.</b>\nt.me/buy_auc/"+str(auc[1])
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="⬅️ Назад к ставкам", callback_data="my_action="+str(msg_id)+"=0"));
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, parse_mode="HTML",reply_markup=keyboard_)
elif call.data.find("account_bill=")>=0:
arg = call.data.split("=");
msg_id = arg[1];
print(msg_id)
user_info = dbworker.get_user(call.message.chat.id)
if user_info[2]==None:
user_info[2]=0;
reply = "<b>🔍Операции со счетом</b>\n\n<b>💳 На твоем счету:</b> "+str(user_info[2])+" грн\n\nТы всегда можешь пополнить счет по кнопке внизу 👇";
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="💰 Пополнить счет", callback_data="balance_get_amount="+str(msg_id)));
keyboard_.row(types.InlineKeyboardButton(text="⬅️ Назад", callback_data="menu="+str(msg_id)));
dbworker.set_state(call.message.chat.id, 0)
#bot.register_next_step_handler(call.message, check_text)
bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, parse_mode="HTML",reply_markup=keyboard_)
elif call.data.find("balance_get_amount=")>=0:
arg = call.data.split("=");
reply = "⚡️ Выберите сумму на которую хотите пополнить счет или введите её сами\n\n<b>🔥 Минимум 50 грн 🔥</b>"
msg_id = arg[1]
keyboard_ = types.InlineKeyboardMarkup()
keyboard_.row(types.InlineKeyboardButton(text="50 грн", callback_data="balance_add="+str(msg_id)+"=5000"),types.InlineKeyboardButton(text="100 грн", callback_data="balance_add="+str(msg_id)+"=10000"));
keyboard_.row(types.InlineKeyboardButton(text="200 грн", callback_data="balance_add="+str(msg_id)+"=20000"),types.InlineKeyboardButton(text="500 грн", callback_data="balance_add="+str(msg_id)+"=50000"));
keyboard_.row(types.InlineKeyboardButton(text="❌ Отмена", callback_data="account_bill="+str(msg_id)))
dbworker.set_state(call.message.chat.id, 1)
msg = bot.edit_message_text(message_id=int(msg_id)+1, chat_id=call.message.chat.id, text=reply, parse_mode="HTML",reply_markup=keyboard_)
elif call.data.find("balance_add=")>=0:#first msg_id second amount of pay
arg = call.data.split("=");
prices = [LabeledPrice(label='Пополнение счета на {} грн'.format(arg[2][:-2]), amount=int(arg[2]))]
bot.send_invoice(call.message.chat.id, title='Пополнение счета на {} грн'.format(arg[2][:-2]),
description='{} грн чтобы делать ставки на аукционе'.format(arg[2][:-2]),
provider_token=provider_token,
currency='uah',
photo_url='http://paint-net.ru/img4/img44/44023.png',
photo_height=414, # !=0/None or picture won't be shown
photo_width=312,
photo_size=512,
is_flexible=False, # True If you need to set up Shipping Fee
prices=prices,
start_parameter='time-machine-example',
invoice_payload='{}'.format(arg[2][:-2]))
def telegram_main(n):
bot.skip_pending = True
try:
bot.polling(none_stop=True,timeout=180)
except:
traceback_error_string=traceback.format_exc()
with open("Error.Log", "a") as myfile:
myfile.write("\r\n\r\n" + time.strftime("%c")+"\r\n<<error polling="">>\r\n"+ traceback_error_string + "\r\n<<error polling="">>")
bot.stop_polling()
time.sleep(10)
def check_for_end(bot, job):
all_auct = dbworker.get_all_active_auctions();
for i in all_auct:
print(i[9])
if datetime.datetime.now()>=datetime.datetime.strptime(i[9], "%Y-%m-%d %H:%M:%S"):
print("NON active")
msg_id = int(i[1]);
description = '<a href="'+str(i[3])+'">Фото</a>\n'+str(i[2])
dbworker.end_auction(int(i[0]));
bot.edit_message_text(message_id=msg_id, chat_id=to_channel, text=description, parse_mode="HTML")
else:
print("active")
if __name__ == '__main__':
print("webhook");
#####RASKOMENTIT' VSE GOTOVO!!!!
#job_minute = j.run_repeating(callback=check_for_end, interval=5, context=(0))
bot.remove_webhook()
# Ставим заново вебхук
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
certificate=open(WEBHOOK_SSL_CERT, 'r'))
cherrypy.config.update({
'server.socket_host': WEBHOOK_LISTEN,
'server.socket_port': WEBHOOK_PORT,
'server.ssl_module': 'builtin',
'server.ssl_certificate': WEBHOOK_SSL_CERT,
'server.ssl_private_key': WEBHOOK_SSL_PRIV
})
# Собственно, запуск!
cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})
telegram_main(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment