- websprojekt
- Автор темы
- Депозит: 1000$
- 129
Бот розыгрышей телеграм.
Команды:
/list - сколько участников присоединились к розыгрышу
/end - выбирает победителя. Победителю и остальным участникам отправляется уведомление о победе
/testend - Проведёт тестовое завершение. Список участников не очищается, сообщения не рассылаются
/check - поможет сделать проверку на подписку перед тем, как определить победителя
Команды:
/list - сколько участников присоединились к розыгрышу
/end - выбирает победителя. Победителю и остальным участникам отправляется уведомление о победе
/testend - Проведёт тестовое завершение. Список участников не очищается, сообщения не рассылаются
/check - поможет сделать проверку на подписку перед тем, как определить победителя
Код Код:
import telebot
from telebot import types
import json
from os.path import isfile
from random import choice
from re import sub
bot = telebot.TeleBot('YOUR_TOKEN')
channels = [-YOUR_CHANNEL_ID]
admins = [ADMIN_ID]
if not isfile('participants.malw'):
with open('participants.malw', 'w') as file:
file.write('[]')
with open('participants.malw', 'r') as file:
participants = json.loads(file.read())
@bot.message_handler(commands=['start'])
def start(message):
global participants, channels
if str(message.from_user.id) in participants:
bot.reply_to(message, 'Ты уже участвуешь в розыгрыше', disable_web_page_preview=True)
return
for channel in channels:
try:
user_info = bot.get_chat_member(channel, message.from_user.id)
if user_info.status not in ['member', 'creator', 'administrator']:
raise
except Exception as e:
channel_info = bot.get_chat(channel)
bot.reply_to(message, f'Ты не подписан на {channel_info.title}', parse_mode='markdown', disable_web_page_preview=True)
return
participants.append(str(message.from_user.id))
with open('participants.malw', 'w') as file:
file.write(json.dumps(participants))
bot.reply_to(message, 'Ты принял участие в розыгрыше', disable_web_page_preview=True)
@bot.message_handler(commands=['check'])
def check(message):
global participants, channels
if message.from_user.id in admins:
for participant in participants:
for channel in channels:
try:
user_info = bot.get_chat_member(channel, participant)
if user_info.status not in ['member', 'creator', 'administrator']:
raise
except Exception as e:
channel_info = bot.get_chat(channel)
try:
bot.send_message(participant, f'Ты вышел из канала {channel_info.title}, поэтому больше не участвуешь в розыгрыше', parse_mode='markdown', disable_web_page_preview=True)
except:
pass
participants.remove(participant)
break
with open('participants.malw', 'w') as file:
file.write(json.dumps(participants))
bot.reply_to(message, 'Проверка завершена', disable_web_page_preview=True)
@bot.message_handler(commands=['end'])
def end(message):
global participants
if message.from_user.id in admins:
if not participants:
bot.reply_to(message, 'В розыгрыше никто не участвует', disable_web_page_preview=True)
return
winner = choice(participants)
winner_name = bot.get_chat(winner)
for ts in sub('[A-Za-zА-Яа-я0-9 ]', '', winner_name.first_name):
winner_name.first_name = winner_name.first_name.replace(ts, '')
if winner_name.first_name.replace(' ', '') == '':
winner_name.first_name = 'Пустой или засранный ник'
if winner_name.username:
name = f'[{winner_name.first_name}](https://t.me/{winner_name.username})\n'
elif not hasattr(winner_name, "has_private_forwards"):
name = f'[{winner_name.first_name}](tg://user?id={winner})\n'
else:
name = f'{winner_name.first_name} (невозможно упомянуть)\n'
for participant in participants:
try:
bot.send_message(int(participant), f'Честная система рандома определила победителя этого розыгрыша. Им становится {name}', parse_mode='markdown', disable_web_page_preview=True)
except:
pass
bot.reply_to(message, f'Честная система рандома определила победителя этого розыгрыша. Им становится {name}', parse_mode='markdown', disable_web_page_preview=True)
with open('participants_old.malw', 'w') as file:
file.write(json.dumps(participants))
participants = []
with open('participants.malw', 'w') as file:
file.write(json.dumps(participants))
@bot.message_handler(commands=['testend'])
def testend(message):
global participants
if message.from_user.id in admins:
if not participants:
bot.reply_to(message, 'В розыгрыше никто не участвует', disable_web_page_preview=True)
return
winner = choice(participants)
winner_name = bot.get_chat(winner)
for ts in sub('[A-Za-zА-Яа-я0-9 ]', '', winner_name.first_name):
winner_name.first_name = winner_name.first_name.replace(ts, '')
if winner_name.first_name.replace(' ', '') == '':
winner_name.first_name = 'Пустой или засранный ник'
if winner_name.username:
name = f'[{winner_name.first_name}](https://t.me/{winner_name.username})\n'
elif not hasattr(winner_name, "has_private_forwards"):
name = f'[{winner_name.first_name}](tg://user?id={winner})\n'
else:
name = f'{winner_name.first_name} (невозможно упомянуть)\n'
bot.reply_to(message, f'Тестовое завершение. Список участников не очищается и сообщения не рассылаются. Честная система рандома определила победителя этого розыгрыша. Им становится {name}', parse_mode='markdown', disable_web_page_preview=True)
@bot.message_handler(commands=['list'])
def list_participants(message):
global participants
if message.from_user.id in admins:
if not participants:
bot.reply_to(message, 'В розыгрыше никто не участвует', disable_web_page_preview=True)
return
participants_list = ''
for participant in participants:
participant_info = bot.get_chat(participant)
for ts in sub('[A-Za-zА-Яа-я0-9 ]', '', participant_info.first_name):
participant_info.first_name = participant_info.first_name.replace(ts, '')
if participant_info.first_name.replace(' ', '') == '':
participant_info.first_name = 'Пустой или засранный ник'
if participant_info.username:
participants_list += f'[{participant_info.first_name}](https://t.me/{participant_info.username})\n'
elif not hasattr(participant_info, "has_private_forwards"):
participants_list += f'[{participant_info.first_name}](tg://user?id={participant})\n'
else:
participants_list += f'{participant_info.first_name} (невозможно упомянуть)\n'
bot.reply_to(message, 'Список участников розыгрыша:\n' + participants_list, parse_mode='markdown', disable_web_page_preview=True)
bot.polling(none_stop=True)