Exemplo n.º 1
0
    def __init__(self, username, client_id, token, channel):
        self.client_id = client_id
        self.token = token
        self.channel = '#' + channel
        self.accounts_controller = AccountsController()
        self.commands_controller = CommandsController()
        self.telegram_notifier = TelegramNotifier()
        self.twitch_client = TwitchClient()
        self.is_duel_on = False

        # Get the channel id, we will need this for v5 API calls
        url = 'https://api.twitch.tv/kraken/users?login='******'Client-ID': client_id,
            'Accept': 'application/vnd.twitchtv.v5+json'
        }
        r = requests.get(url, headers=headers).json()
        self.channel_id = r['users'][0]['_id']
        logger.info(self.channel_id)

        # Create IRC bot connection
        server = 'irc.twitch.tv'
        port = 6667
        logger.info('Connecting to ' + server + ' on port ' + str(port) +
                    '...')
        irc.bot.SingleServerIRCBot.__init__(self,
                                            [(server, port, 'oauth:' + token)],
                                            username, username)
Exemplo n.º 2
0
async def main():
    from datetime import datetime
    t = perf_counter()
    some_name = 'emilybarkiss'
    sample_sz = 300
    n_consumers = 100

    async with TwitchClient() as tc:
        streamer = await Streamer().create(tc, some_name)
        str_pipe = StreamerPipe(streamer, sample_sz=sample_sz)
        folnet = FollowerNetwork(streamer_id=streamer.uid)
        folnet_pipe = FollowNetPipe(folnet, 200)
        live_streams = LiveStreams()
        ls_pipe = LiveStreamPipe(live_streams)
        await run(tc=tc, str_pipe=str_pipe, folnet_pipe=folnet_pipe, ls_pipe=ls_pipe, n_consumers=n_consumers)

        streamer.display
        str_pipe.display
        folnet_pipe.display
        ls_pipe.display

        print(f'{Col.magenta}🟊 N consumers: {n_consumers} {Col.end}')
        print(f'{Col.orange}[📞] Total Calls to Twitch: {tc.http.count_success_resp} {Col.end}')
        print(f'{Col.cyan}⏲ Total Time: {round(perf_counter() - t, 3)} sec {Col.end}')
        print(f'{Col.red}\t««« {datetime.now().strftime("%I:%M.%S %p")} »»» {Col.end}')
Exemplo n.º 3
0
    async def __call__(self, n_consumers=100):
        t = perf_counter()

        async with TwitchClient() as tc:
            await self.streamer.create(tc)
            # self.pipeline = RecommendationPipeline(self.streamer, self.folnet, self.live_streams)
            await self.pipeline(tc, n_consumers)

            self.streamer.display
            self.pipeline.streamer_pipe.display
            self.pipeline.folnet_pipe.display
            self.pipeline.live_stream_pipe.display

            self.get_sims()

            print(f'{Col.magenta}[🟊] N consumers: {n_consumers} {Col.end}')
            print(
                f'{Col.green}[🟊] Max Followings: {self.max_followings} {Col.end}'
            )
            print(
                f'{Col.orange}[📞] Total Calls to Twitch: {tc.http.count_success_resp} {Col.end}'
            )
            print(
                f'{Col.white}\t(Token bucket: {tc.http._bucket.tokens}{Col.end})'
            )
            print(
                f'{Col.cyan}[⏲] Total Time: {round(perf_counter() - t, 3)} sec {Col.end}'
            )
            print(
                f'{Col.red}\t««« {datetime.now().strftime("%I:%M.%S %p")} »»» {Col.end}'
            )
Exemplo n.º 4
0
async def main():
    t = perf_counter()
    some_name = 'emilybarkiss'
    sample_sz = 350
    n_consumers = 100
    max_followings = 200

    async with TwitchClient() as tc:
        streamer = await Streamer().create(tc, some_name)
        streamer_pipe = StreamerPipe(streamer, sample_sz=sample_sz)
        folnet = FollowerNetwork(streamer_id=streamer.uid)
        folnet_pipe = FollowNetPipe(folnet, max_followings)
        await folnet_pipe.run(tc, streamer_pipe, n_consumers=n_consumers)

        streamer.display
        streamer_pipe.display
        folnet_pipe.display

        print(f'{Col.magenta}[🟊] N consumers: {n_consumers} {Col.end}')
        print(f'{Col.green}[🟊] Max Followings: {max_followings} {Col.end}')
        print(
            f'{Col.orange}[📞] Total Calls to Twitch: {tc.http.count_success_resp} {Col.end}'
        )
        print(
            f'{Col.cyan}[⏲] Total Time: {round(perf_counter() - t, 3)} sec {Col.end}'
        )
        from datetime import datetime
        print(
            f'{Col.red}\t««« {datetime.now().strftime("%I:%M.%S %p")} »»» {Col.end}'
        )
async def main():
    from colors import Col
    from datetime import datetime
    from time import perf_counter
    t = perf_counter()

    some_name = 'emilybarkiss'
    sample_sz = 350
    n_consumers = 100

    async with TwitchClient() as tc:
        streamer = Streamer(name=some_name)
        folnet = FollowerNetwork(streamer.uid)
        livestreams = LiveStreams()

        pipeline = RecommendationPipeline(streamer, folnet, livestreams,
                                          sample_sz)
        await pipeline(tc, n_consumers)

    streamer.display
    pipeline.folnet_pipe.display
    pipeline.live_stream_pipe.display

    print(f'{Col.magenta}🟊 N consumers: {n_consumers} {Col.end}')
    print(
        f'{Col.cyan}⏲ Total Time: {round(perf_counter() - t, 3)} sec {Col.end}'
    )
    print(
        f'{Col.red}\t««« {datetime.now().strftime("%I:%M.%S %p")} »»» {Col.end}'
    )
Exemplo n.º 6
0
async def main():
    from time import perf_counter
    t = perf_counter()

    some_name = 'emilybarkiss'
    sample_sz = 350

    async with TwitchClient() as tc:
        streamer = await Streamer(some_name).create(tc)
        str_pipe = StreamerPipe(streamer, sample_sz=sample_sz)
        await str_pipe(tc)

    streamer.display
    str_pipe.display
    print(f'{Col.orange}[📞] Total Calls to Twitch: {tc.http.count_success_resp} {Col.end}')
    print(f'{Col.cyan}[�] Total Time: {round(perf_counter() - t, 3)} sec {Col.end}')
Exemplo n.º 7
0
def login(request):
    s = request.session
    if s.get('state')!=None:
        client = TwitchClient(app_settings.CLIENT_ID, OAuth2AccessToken.objects.get(account_id=s.get("_auth_user_id")))
        user = TwitchAccount.objects.get(user_id=s.get("_auth_user_id"))
        logo = user.get_avatar_url()
        name = user.get_name()
        logger.error(s.get("_auth_user_id"))
        if (str(name).lower()=="dezelon".lower() or str(name).lower()=="grandleon".lower()): #grandleon
            data = {
                'status': 200,
                'role': 'author',
                'logo': logo,
                'name': name,
            }
        else:
            data = client.users.check_subscribed_to_channel(user.uid, "grandleon")
            data['role'] = 'user'
            data['logo'] = logo
            data['name'] = name
    else:
        data = {
            'status': 'login',
            'role': 'user',
        }

    if data['status'] == 200:
        data['form'] = UserLoginForm(request.POST or None)
        logger.error(data['form'])
        if request.method == 'POST' and data['form'].is_valid():
            # old_nickname = data['form'].cleaned_data.get('old_nickname', None)
            nickname = data['form'].cleaned_data.get('nickname', None)
            try:
                whitelist_obj = DBWhitelist.objects.using('db_whitelist').get(user_id = s.get("_auth_user_id"))
                whitelist_obj.old_nickname = whitelist_obj.nickname
            except DBWhitelist.DoesNotExist:
                logger.error("2 " + s.get("_auth_user_id"))
                whitelist_obj = DBWhitelist()
                whitelist_obj.user_id = s.get("_auth_user_id")
                whitelist_obj.old_nickname = None
            whitelist_obj.sub_twitch = True
            whitelist_obj.nickname = nickname
            whitelist_obj.in_whitelist = False
            whitelist_obj.save(using='db_whitelist')

    return render(request, "login/index.html", locals())
Exemplo n.º 8
0
import config
from twitch_client import TwitchClient

from commands.snap import SnapCommand
from commands.thanos import ThanosCommand

import traceback

client = TwitchClient(config.HOST, config.PORT, config.NICK, config.PASS,
                      config.CHANNEL)

client.connect()

#def on_message(user, msg):
#  client.send_message(msg)

#client.on("message", on_message)

client.register_command(SnapCommand())
client.register_command(ThanosCommand())

while (True):
    try:
        client.run()
    except KeyboardInterrupt:
        raise
    except:
        print(traceback.format_exc())
        client = TwitchClient(config.HOST, config.PORT, config.NICK,
                              config.PASS, config.CHANNEL)
        client.connect()
Exemplo n.º 9
0
class TwitchBot(irc.bot.SingleServerIRCBot):
    def __init__(self, username, client_id, token, channel):
        self.client_id = client_id
        self.token = token
        self.channel = '#' + channel
        self.accounts_controller = AccountsController()
        self.commands_controller = CommandsController()
        self.telegram_notifier = TelegramNotifier()
        self.twitch_client = TwitchClient()
        self.is_duel_on = False

        # Get the channel id, we will need this for v5 API calls
        url = 'https://api.twitch.tv/kraken/users?login='******'Client-ID': client_id,
            'Accept': 'application/vnd.twitchtv.v5+json'
        }
        r = requests.get(url, headers=headers).json()
        self.channel_id = r['users'][0]['_id']
        logger.info(self.channel_id)

        # Create IRC bot connection
        server = 'irc.twitch.tv'
        port = 6667
        logger.info('Connecting to ' + server + ' on port ' + str(port) +
                    '...')
        irc.bot.SingleServerIRCBot.__init__(self,
                                            [(server, port, 'oauth:' + token)],
                                            username, username)

    def on_welcome(self, c, e):
        logger.info('Joining ' + self.channel)

        # You must request specific capabilities before you can use them
        c.cap('REQ', ':twitch.tv/membership')
        c.cap('REQ', ':twitch.tv/tags')
        c.cap('REQ', ':twitch.tv/commands')
        c.join(self.channel)

    def on_pubmsg(self, c, e):
        # If a chat message starts with an exclamation point, try to run it as a command
        if e.arguments[0][:1] == '!':
            receiver_name = e.tags[2]['value'].lower()
            cmd = e.arguments[0].split(' ')[0][1:]
            logger.info('Received command: {} from: {}'.format(
                cmd, receiver_name))
            self.do_command(e, cmd)
        message = str(e.arguments[0]).lower()
        if notifier_triggers[0] in message or notifier_triggers[1] in message:
            self.telegram_notifier.send_message(message=message)
        return

    def do_command(self, e, cmd):
        c = self.connection
        receiver_name = e.tags[2]['value'].lower()
        # to add new command add if cmd.startswith('command'):

        # TODO: Need to move all commands to another place
        # register to duels
        if cmd.startswith('reg'):
            if not self.is_duel_on:
                return
            appended = self.accounts_controller.append_account(
                account_name=receiver_name)
            if not appended:
                return
            c.privmsg(self.channel,
                      text='{} зареган EZ !duel для инфы по дуэлям]'.format(
                          receiver_name))

        # get duel stats
        if cmd.startswith('stats_duel'):
            accounts = self.accounts_controller.get_accounts()
            if receiver_name in accounts:
                win_count = self.accounts_controller.get_win_count(
                    receiver_name)
                c.privmsg(self.channel,
                          text='{} Количество побед: {}'.format(
                              receiver_name, win_count))

        # get top 5 duelists
        if cmd.startswith('best_duelists'):
            if receiver_name not in moders_white_list:
                return
            report = self.accounts_controller.get_top5()
            c.privmsg(self.channel, text=str(report))

        # start duel
        if cmd.startswith('duel'):
            if not self.is_duel_on:
                return
            accounts = self.accounts_controller.get_accounts()
            enemy_name = e.arguments[0].replace('!duel ', '').lower()
            if receiver_name in moders_list:
                c.privmsg(self.channel,
                          text='{} умный самый? Дисреспект за абуз'.format(
                              receiver_name))
                return
            if enemy_name == '!duel':
                c.privmsg(self.channel,
                          text='{} !duel [имя зереганного челика]'.format(
                              receiver_name))
                logger.info('started duel: {} vs {}'.format(
                    receiver_name, enemy_name))
                return
            elif enemy_name not in accounts:
                c.privmsg(self.channel,
                          text='{} твой чел не зареган'.format(receiver_name))
                return
            elif receiver_name not in accounts:
                c.privmsg(self.channel,
                          text='{} зарегайся !reg'.format(receiver_name))
                return
            loser = self.accounts_controller.get_account_duel_result(
                receiver_name, enemy_name)
            if not loser:
                logger.error('duel was failed')
                return
            c.privmsg(self.channel,
                      text='/timeout {} {}'.format(loser,
                                                   random.randint(1, 600)))
            logger.info('loser is {}'.format(loser))

        # turn on duels
        if cmd.startswith('turn_off_duel'):
            if receiver_name not in moders_white_list:
                return
            self.is_duel_on = False
            c.privmsg(self.channel, text='Дуэли вырублены, мечи в ножны!')

        # turn off duels
        if cmd.startswith('turn_on_duel'):
            if receiver_name not in moders_white_list:
                return
            self.is_duel_on = True
            c.privmsg(
                self.channel,
                text=
                'SMOrc Дуэли активированы !reg для реги !duel для сражений SMOrc'
            )

        # change game
        if cmd.startswith('change_game'):
            if receiver_name not in moders_white_list:
                return
            game = e.arguments[0].replace('!{} '.format(cmd), '')
            is_game_changed = self.twitch_client.change_game(game=game)
            if is_game_changed:
                c.privmsg(self.channel, text='Игра сменена на {}'.format(game))
            else:
                c.privmsg(
                    self.channel,
                    text='чот не получилось игру установить сори FeelsBadMan')

        if cmd.startswith('ебануть_команду'):
            if receiver_name not in moders_white_list:
                return
            new_command_list = str(e.arguments[0]).split(' ')
            print(new_command_list)
            print(len(new_command_list))
            if len(new_command_list) != 3:
                c.privmsg(
                    self.channel,
                    text=
                    'Дурачок, команда подана неправильно. Образец !ебануть_команду имя_команды ответ_ответ вместо пробела _'
                )
                return
            command_name = new_command_list[1]
            command_answer = str(new_command_list[2]).replace("_", " ")
            c.privmsg(self.channel,
                      text=self.commands_controller.create_command(
                          command_name=command_name,
                          command_answer=command_answer))

        if cmd.startswith('удали_команду'):
            if receiver_name not in moders_white_list:
                return
            command = str(e.arguments[0]).split(' ')[1]
            c.privmsg(self.channel,
                      text=self.commands_controller.delete_command(
                          command_name=command))

        if cmd.startswith('обнови_команду'):
            if receiver_name not in moders_white_list:
                return
            new_command_list = str(e.arguments[0]).split(' ')
            if len(new_command_list) != 3:
                c.privmsg(
                    self.channel,
                    text=
                    'Дурачок, команда подана неправильно. Образец !обнови_команду имя_команды новое_значение вместо пробела _'
                )
                return
            command_name = new_command_list[1]
            command_answer = str(new_command_list[2]).replace("_", " ")
            c.privmsg(self.channel,
                      text=self.commands_controller.update_command(
                          command_name=command_name, new_value=command_answer))

        if cmd.startswith('получить_команды'):
            if receiver_name not in moders_white_list:
                return
            c.privmsg(self.channel,
                      text=self.commands_controller.get_all_cmds())

        if cmd:
            msg = self.commands_controller.execute_command(cmd)
            if msg:
                c.privmsg(self.channel, text=msg)
Exemplo n.º 10
0
import os
import sys

sys.path.append(
    os.path.realpath(
        os.path.join(os.getcwd(), "..", "stream_backend/api/utils")))

sys.path.append(
    os.path.realpath(os.path.join(os.getcwd(), "..", "stream_backend")))

from twitch_client import TwitchClient

client = TwitchClient()