summaryrefslogtreecommitdiff
path: root/tgbot.py
blob: c8561cdb33a3b10ea8ff28b91f5f76fb85558fc0 (plain)
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
#!/usr/bin/python3

import os
import time, threading, schedule
import telebot
import asyncio
import telebot.async_telebot
from FortniteStatusWrapper import *
from FortniteStatusFormatter import *
from FortniteClient import *
from FortniteEvents import *
from persistence import UserRepository
from datetime import datetime

if "TELEBOT_BOT_TOKEN" not in os.environ:
    raise AssertionError("Please configure TELEBOT_BOT_TOKEN as environment variables")

#bot = telebot.TeleBot(os.environ["TELEBOT_BOT_TOKEN"])
bot = telebot.async_telebot.AsyncTeleBot(os.environ["TELEBOT_BOT_TOKEN"])
userRepository = UserRepository('db.sqlite')
fortniteStatusWrapper = FortniteStatusWrapper()
fortniteClient = FortniteClient()

@bot.message_handler(commands = ['start'])
async def startCommand(message):
    userRepository.putUser(message.chat.id)
    await bot.reply_to(message, "This chat successfully registered to receive Fortnite updates!")

@bot.message_handler(commands = ['status'])
async def getStatus(message):
    await bot.reply_to(
        message,
        formatFortniteStatus(fortniteStatus.getStatus()),
        parse_mode='MarkdownV2')

@bot.message_handler(commands = ['friends'])
async def getFriends(message):
    await bot.reply_to(
        message,
        formatFriends(fortniteClient.get_friends()),
        parse_mode='MarkdownV2')

@bot.message_handler(commands = ['find'])
async def findUser(message):
    arg = message.text.split()
    if len(arg) > 1:
        search_user_display_name = arg[1]
        print('Searching users by name {}'.format(search_user_display_name))
        users: typing.List[fortnitepy.User] = await fortniteClient.fetch_users_by_display_name(search_user_display_name)
        for user in users:
            stats = await user.fetch_br_stats()
            await bot.reply_to(
                message,
                formatUser(user, stats),
                parse_mode='MarkdownV2')
    else:
        await bot.reply_to(
                message,
                'Usage: /find username',
                parse_mode='MarkdownV2')

@bot.message_handler(commands = ['add'])
async def addUser(message):
    arg = message.text.split()
    if len(arg) > 1:
        user_id = arg[1]
        print('Adding user with ID as friend {}'.format(user_id))
        await fortniteClient.add_friend(user_id)
        await bot.reply_to(
                message,
                'Send friend request successfully',
                parse_mode='MarkdownV2')
    else:
        await bot.reply_to(
                message,
                'Usage: /add username',
                parse_mode='MarkdownV2')

class FortniteStatusObserver(Observer):
    def update(self, fortniteStatus) -> None:
        for user in userRepository.getAllUsers():
            bot.send_message(
                user[0],
                formatFortniteStatus(fortniteStatus),
                parse_mode='MarkdownV2'
            )

class FortnitePresenceObserver(PresenceObserver):

    # Map name -> last seen not playing timestamp seconds
    statuses = {}

    def update(self, display_name: str, playing: bool) -> None:
        print('FortnitePresenceObserver: {} playing = {}'.format(display_name, playing))
        if playing:
            if not display_name in self.statuses:
                self.__notifyFriendPlaying(display_name)
                self.statuses[display_name] = time.time()
            else:
                diff = time.time() - self.statuses[display_name]
                if diff > 60 * 60: # 60 minutes
                     self.__notifyFriendPlaying(display_name)
        else:
            self.statuses[display_name] = time.time()

    def __notifyFriendPlaying(self, display_name: str):
        for user in userRepository.getAllUsers():
            bot.send_message(
                user[0],
                '{} is online'.format(display_name),
                parse_mode='MarkdownV2'
            )

async def run_bot():
    await bot.polling()

async def run_client():
    await fortniteClient.run()

if __name__ == '__main__':
    fortniteStatusWrapper.attach(FortniteStatusObserver())
    fortniteClient.attach(FortnitePresenceObserver())

    loop = asyncio.get_event_loop()
    loop.create_task(bot.polling())
    loop.create_task(fortniteClient.run())
    loop.run_forever()