Skip to content

Commit

Permalink
feat: clean up stale games
Browse files Browse the repository at this point in the history
  • Loading branch information
d-Rickyy-b committed Aug 1, 2021
1 parent 52ee6e7 commit 1e449a7
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
4 changes: 3 additions & 1 deletion blackjack/game/blackjackgame.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
import logging

from datetime import datetime
from enum import Enum

import blackjack.errors as errors
from blackjack.game import Player, Dealer, Deck

Expand All @@ -17,6 +18,7 @@ def __init__(self, gametype=None, game_id=None, lang_id="en"):
self.list_won = []
self.list_tie = []
self.list_lost = []
self.datetime_started = datetime.now()
self.bets_active = True
self._current_player = 0
self.players = []
Expand Down
18 changes: 18 additions & 0 deletions blackjackbot/gamestore.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta
from random import randint

from .errors.noactivegameexception import NoActiveGameException
Expand Down Expand Up @@ -82,3 +83,20 @@ def _game_stopped_callback(self, game):
self.remove_game(self._game_dict[game.id])

self.logger.debug("Current games: {}".format(len(self._chat_dict)))

def cleanup_stale_games(self):
stale_timeout_min = 10
now = datetime.now()
remove_chat_ids = []

for game_id, chat_id in self._game_dict.items():
game = self.get_game(chat_id)

game_older_than_10_mins = game.datetime_started < (now - timedelta(minutes=stale_timeout_min))
if game_older_than_10_mins:
logging.info("Killing game with id {} because it's stale for > {} mins".format(game.id, stale_timeout_min))
# TODO notify chat
remove_chat_ids.append(chat_id)

for chat_id in remove_chat_ids:
self.remove_game(chat_id)
13 changes: 12 additions & 1 deletion bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
import logging.handlers
import pathlib

from telegram.ext import Updater
from telegram.ext import Updater, JobQueue

import config
from blackjackbot import handlers, error_handler
from blackjackbot.gamestore import GameStore

logdir_path = pathlib.Path(__file__).parent.joinpath("logs").absolute()
logfile_path = logdir_path.joinpath("bot.log")
Expand All @@ -32,6 +33,16 @@

updater.dispatcher.add_error_handler(error_handler)


# Set up jobs
def stale_game_cleaner(context):
gs = GameStore()
gs.cleanup_stale_games()


updater.job_queue.run_repeating(callback=stale_game_cleaner, interval=300, first=300)


if config.USE_WEBHOOK:
updater.start_webhook(listen=config.WEBHOOK_IP, port=config.WEBHOOK_PORT, url_path=config.BOT_TOKEN, cert=config.CERTPATH, webhook_url=config.WEBHOOK_URL)
updater.bot.set_webhook(config.WEBHOOK_URL)
Expand Down

0 comments on commit 1e449a7

Please sign in to comment.