Skip to content

Commit

Permalink
Added "Winner Of The Day" (#14)
Browse files Browse the repository at this point in the history
Also sending clickable result of spin w/o notification (part 1)
  • Loading branch information
evgfilim1 committed Aug 29, 2017
1 parent baafd02 commit aea5280
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 38 deletions.
63 changes: 41 additions & 22 deletions core.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ def emit(self, record):
auto_spin_jobs = {}
chat_config = {}
languages = {}
wotd_registered = []
wotd = 0

announcement_chats = []
log = None
Expand Down Expand Up @@ -137,7 +139,7 @@ def _load_lang():

def _load_all():
global chat_users, usernames, spin_name, can_change_name, results_today, results_total
global auto_spins, chat_config
global auto_spins, chat_config, wotd_registered, wotd
chat_users = _load("users.pkl")
usernames = _load("unames.pkl")
spin_name = _load("spin.pkl")
Expand All @@ -146,6 +148,8 @@ def _load_all():
results_total = _load("total.pkl")
auto_spins = _load("auto.pkl")
chat_config = _load("config.pkl")
wotd_registered = _load("wotdreg.pkl", default=list)
wotd = _load("wotdwin.pkl", default=int)
_load_lang()


Expand All @@ -158,6 +162,8 @@ def save_all():
_save(auto_spins, "auto.pkl")
_save(chat_config, "config.pkl")
_save(usernames, "unames.pkl")
_save(wotd, "wotdwin.pkl")
_save(wotd_registered, "wotdreg.pkl")


def clear_data(chat_id: int):
Expand Down Expand Up @@ -202,29 +208,42 @@ def str_to_time(s: str) -> time:
return time((hours + offset) % 24, minutes, tzinfo=None)


def choose_random_user(chat_id: int, bot: Bot) -> str:
def choose_random_user(chat_id: int, bot: Bot) -> int:
global wotd
from random import choice
user_id = choice(chat_users[chat_id])
username = usernames.get(user_id, f"id{user_id}")
try:
member = bot.get_chat_member(chat_id=chat_id, user_id=user_id)
if is_user_left(member):
raise TelegramError("User left the group")
if member.user.name == '':
usernames.update({user_id: f"DELETED/id{user_id}"})
raise TelegramError("User deleted from Telegram")
except TelegramError as e:
chat_users[chat_id].pop(chat_users[chat_id].index(user_id))
log.debug(f"{e}. User info: {(user_id, username)}, chat_id: {chat_id}")
if chat_id:
user_id = choice(chat_users[chat_id])
try:
member = bot.get_chat_member(chat_id=chat_id, user_id=user_id)
if is_user_left(member):
raise TelegramError("User left the group")
except TelegramError as e:
chat_users[chat_id].pop(chat_users[chat_id].index(user_id))
log.debug(f"{e}. User_id: {user_id}, chat_id: {chat_id}")
return choose_random_user(chat_id, bot)
user = member.user
else:
user_id = choice(wotd_registered)
user = bot.get_chat(user_id)
if user.first_name == '':
usernames.update({user_id: f"DELETED/id{user_id}"})
return choose_random_user(chat_id, bot)
user = member.user.name
uid = member.user.id
results_today.update({chat_id: user})
usernames.update({uid: user})
if chat_id not in results_total:
results_total.update({chat_id: {}})
results_total[chat_id].update({uid: results_total[chat_id].get(uid, 0) + 1})
return user
# Waiting for PR #809 to merge, now using this behaviour
if user.username:
name = f'@{user.username}'
elif user.last_name:
name = f'{user.first_name} {user.last_name}'
else:
name = user.first_name
if chat_id:
results_today.update({chat_id: user.id})
if chat_id not in results_total:
results_today.update({chat_id: {}})
results_total[chat_id].update({user.id: results_total[chat_id].get(user.id, 0) + 1})
else:
wotd = user.id
usernames.update({user.id: name})
return user.id


def top_win(chat_id: int) -> list:
Expand Down
13 changes: 12 additions & 1 deletion lang/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ check_pm: "Отправлено в ЛС"
default_spin_name: "ноунейм"
spin_name_current: "Текущее название розыгрыша: *{0} дня*"
spin_name_changed: "Текст розыгрыша изменён на *{0} дня*"
already_spin: "Согласно сегодняшнему розыгрышу, *{s} дня* — `{n}`"
wotd: "победитель глобального розыгрыша"
wotd_already_reg: "Ты уже зарегистрирован"
wotd_registered: "Теперь ты участвуешь в глобальном розыгрыше"
wotd_nostats: "Ещё никто не победил в глобальном розыгрыше"
already_spin: "Согласно сегодняшнему розыгрышу, *{s} дня* — {n}"
default_spin_texts:
-
- "Итак, кто же сегодня *{s} дня*?"
Expand Down Expand Up @@ -111,6 +115,13 @@ help_texts:
'':
text: "Запустить розыгрыш. Если розыгрыш уже был произведён в чате,
показать результат"
winner:
summary: Победитель глобального розыгрыша дня!
usage:
'':
text: Узнать результат глобального розыгрыша
register:
text: Принять участие в глобальном розыгрыше
auto:
summary: Управление автоматическими розыгрышами.
usage:
Expand Down
56 changes: 41 additions & 15 deletions thebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,13 @@ def handle_error(bot: Bot, update: Update, error):
log.error(f"Update {update} caused error: {error}")


def reset(bot: Bot = None, job: Job = None):
def daily_job(bot: Bot, job: Job = None):
core.results_today.clear()
log.debug("Reset done")
uid = core.choose_random_user(0, bot)
text = choice(core.get_lang(uid, 'default_spin_texts'))[-1]
bot.send_message(uid, text.format(s=core.get_lang(uid, 'wotd'), n=core.usernames.get(uid)),
parse_mode=ParseMode.MARKDOWN)


def auto_save(bot: Bot = None, job: Job = None):
Expand Down Expand Up @@ -153,7 +157,7 @@ def admin_shell(bot: Bot, update: Update, args: list):
eval(" ".join(args))
), parse_mode=ParseMode.MARKDOWN, reply_to_message_id=msg.message_id)
elif cmd == "reset":
reset(bot, None)
daily_job(bot, None)
elif cmd == "respin":
if len(args) > 0:
chat = int(args[0])
Expand Down Expand Up @@ -291,41 +295,42 @@ def about(bot: Bot, update: Update):
@core.not_pm
def do_the_spinn(bot: Bot, update: Update):
chat_id = update.message.chat_id
s = escape_markdown(core.spin_name.get(chat_id, core.get_lang(chat_id, 'default_spin_name')))
p = core.results_today.get(chat_id)
if p is None or chat_id in locks:
spin_name = escape_markdown(core.spin_name.get(chat_id, core.get_lang(chat_id, 'default_spin_name')))
winner = core.results_today.get(chat_id)
if winner is None or chat_id in locks:
return
bot.send_message(chat_id=chat_id,
text=core.get_lang(chat_id, 'already_spin').format(s=s, n=update.message.from_user.name),
text=core.get_lang(chat_id, 'already_spin').format(s=spin_name, n=update.message.from_user.name),
parse_mode=ParseMode.MARKDOWN)


@run_async
@core.not_pm
def do_the_spin(bot: Bot, update: Update):
chat_id = update.message.chat_id
s = escape_markdown(core.spin_name.get(chat_id, core.get_lang(chat_id, 'default_spin_name')))
p = core.results_today.get(chat_id)
spin_name = escape_markdown(core.spin_name.get(chat_id, core.get_lang(chat_id, 'default_spin_name')))
winner = core.results_today.get(chat_id)
if chat_id in locks:
return
if p is not None:
bot.send_message(chat_id=chat_id, text=core.get_lang(chat_id, 'already_spin').format(s=s, n=p),
parse_mode=ParseMode.MARKDOWN)
if winner is not None:
winner = core.usernames.get(winner, f'id{winner}')
bot.send_message(chat_id=chat_id, text=core.get_lang(chat_id, 'already_spin').format(s=spin_name, n=winner),
parse_mode=ParseMode.MARKDOWN, disable_notification=True)
else:
if core.get_config_key(chat_id, 'restrict', default=False) and \
not core.is_admin_for_bot(chat_id, update.message.from_user.id, bot):
update.message.reply_text(core.get_lang(chat_id, 'spin_restricted'))
return
p = escape_markdown(core.choose_random_user(chat_id, bot))
winner = escape_markdown(core.usernames.get(core.choose_random_user(chat_id, bot)))
from time import sleep
curr_text = choice(core.get_lang(chat_id, 'default_spin_texts'))
locks.append(chat_id)
if core.get_config_key(chat_id, 'fast', default=False):
bot.send_message(chat_id=chat_id, text=curr_text[-1].format(s=s, n=p),
bot.send_message(chat_id=chat_id, text=curr_text[-1].format(s=spin_name, n=winner),
parse_mode=ParseMode.MARKDOWN)
else:
for t in curr_text:
bot.send_message(chat_id=chat_id, text=t.format(s=s, n=p),
bot.send_message(chat_id=chat_id, text=t.format(s=spin_name, n=winner),
parse_mode=ParseMode.MARKDOWN)
sleep(2)
locks.pop(locks.index(chat_id))
Expand Down Expand Up @@ -593,8 +598,28 @@ def uptime(bot, update):
update.message.reply_text(core.get_lang(update.message.chat_id, 'uptime').format(datetime.now() - start_time))


def wotd(bot: Bot, update: Update, args: list):
chat_id = update.effective_chat.id
user_id = update.effective_user.id
if len(args) == 0:
if core.wotd:
update.message.reply_text(core.get_lang(chat_id, 'already_spin').format(
s=core.get_lang(chat_id, 'wotd'), n=core.usernames.get(core.wotd)
), parse_mode=ParseMode.MARKDOWN, disable_notification=True)
else:
update.message.reply_text(core.get_lang(chat_id, 'wotd_nostats'))
else:
cmd = args.pop(0)
if cmd == 'register':
if user_id not in core.wotd_registered:
core.wotd_registered.append(user_id)
update.effective_message.reply_text(core.get_lang(chat_id, 'wotd_registered'))
else:
update.effective_message.reply_text(core.get_lang(chat_id, 'wotd_already_reg'))


jobs.run_repeating(auto_save, 60)
jobs.run_daily(reset, core.str_to_time(config.RESET_TIME))
jobs.run_daily(daily_job, core.str_to_time(config.RESET_TIME))

feedback_handler = ConversationHandler(
entry_points=[CommandHandler('feedback', ask_feedback)],
Expand All @@ -619,6 +644,7 @@ def uptime(bot, update):
dp.add_handler(CommandHandler('stat', top, pass_args=True))
dp.add_handler(CommandHandler('settings', settings))
dp.add_handler(CommandHandler('uptime', uptime))
dp.add_handler(CommandHandler('winner', wotd, pass_args=True))
dp.add_handler(feedback_handler)
dp.add_handler(MessageHandler(Filters.status_update, svc_handler))
dp.add_handler(CallbackQueryHandler(pages_handler, pattern=r"^top:page_[1-9]+[0-9]*$"))
Expand Down

0 comments on commit aea5280

Please sign in to comment.