def twitch_bot(commands: List[Command]) -> None:
    """Launch the Twitch bot"""
    with open("twitch.token", "rt", encoding="utf-8") as token_handle:
        [nick, token, *channels] = token_handle.read().strip().split("::")

    instance = TwitchBot(token, nick, commands, channels)
    instance.run()
Exemple #2
0
def main():

    config = configparser.ConfigParser()
    config.read('config.ini')

    username = config['twitch']['username']
    client_id = config['twitch']['client_id']
    token = config['twitch']['token']
    channel = config['twitch']['channel']
    reward_id = config['twitch']['reward_id']

    devices = config['homeassistant']['devices']
    auth_key = config['homeassistant']['auth_key']
    url = config['homeassistant']['url']

    # print(username)
    # print(client_id)
    # print(token)
    # print(channel)
    # print(devices)
    # print(auth_key)
    # print(url)

    homeassistant = HomeAssistant(devices, url, auth_key)

    bot = TwitchBot(username, client_id, token, channel, reward_id,
                    homeassistant)
    bot.start()
Exemple #3
0
def main():

    if len(sys.argv) != 6:
        print(
            "Usage: twitchbot <username> <token> <channel> <port> <name_pool_size>"
        )
        sys.exit(1)

    username = sys.argv[1]
    token = sys.argv[2]
    channel = sys.argv[3]
    port = int(sys.argv[4])
    name_pool_size = int(sys.argv[5])

    setproctitle.setproctitle(channel)

    #init cache
    names.cache.setup(channel, name_pool_size)

    #start the bot
    twitch_bot = TwitchBot(username, token, channel)
    TwitchBot.start_background(twitch_bot)

    #run server
    serv = Server()
    serv.run(port, channel)
Exemple #4
0
 def activate_bot(self):
     if self.__config is not None:
         self.__bot = TwitchBot("monstreytechnologies", None,
                                self.__config.twitch_token,
                                "monstreytechnologies", self.cb_movement)
         threading.Thread(target=self.__bot.start).start()
     else:
         logging.error("Invalid configuration")
    def _run(self):
        ''' Main function of thread. Runs the twitch bot main loop '''

        try:
            # Build and run bot in _run, so failures in both commands can be caught in failure threshold logic
            self.bot = TwitchBot(self, self.session['channel'],
                                 self.session['nickname'],
                                 self.session['server'], self.session['port'],
                                 self.session['password'])
            self.bot.start()
        except Exception, e:
            print str(e)
class twitchBotThread(QtCore.QThread):
    def __init__(self,
                 parent,
                 ident,
                 session,
                 running=True,
                 failureThreshold=5):
        super(twitchBotThread, self).__init__(parent)
        self.parent = parent
        self.id = ident
        self.session = session
        self.running = running
        self.failureThreshold = failureThreshold

        # Bind parent event for talking through us to chat room
        QtCore.QObject.connect(self.parent,
                               QtCore.SIGNAL("sendIRCMessageToRoom"),
                               self.talk)

    def stop(self):
        self.running = False

    def run(self):

        failures = 0

        while self.running:
            try:
                self._run()
            except:
                failures += 1
                if failures > self.failureThreshold:
                    self.running = False
                else:
                    self.emit(QtCore.SIGNAL("botThreadPartialFailure"),
                              failures, self.failureThreshold)
                    time.sleep(1)
            else:
                self.running = False

    def _run(self):
        ''' Main function of thread. Runs the twitch bot main loop '''

        try:
            # Build and run bot in _run, so failures in both commands can be caught in failure threshold logic
            self.bot = TwitchBot(self, self.session['channel'],
                                 self.session['nickname'],
                                 self.session['server'], self.session['port'],
                                 self.session['password'])
            self.bot.start()
        except Exception, e:
            print str(e)
 def _create_bot(self, name, channels):
     conn = IRCConnection(settings.IRC['SERVER'], settings.IRC['PORT'],
                          settings.IRC['NICK'], settings.IRC['PASSWORD'],
                          self.log_filename)
     bot_db_logger = DatabaseLogger(settings.DATABASE['HOST'],
                                    settings.DATABASE['NAME'],
                                    settings.DATABASE['USER'],
                                    settings.DATABASE['PASSWORD'])
     bot = TwitchBot(name, conn, bot_db_logger, Queue.Queue(),
                     self.log_filename)
     bot.daemon = True
     bot.connect_and_join_channels(channels)
     bot.start()
     return bot
 def _create_bot(self, name, channels):
     conn = IRCConnection(settings.IRC['SERVER'],
                          settings.IRC['PORT'],
                          settings.IRC['NICK'],
                          settings.IRC['PASSWORD'],
                          self.log_filename)
     bot_db_logger = DatabaseLogger(settings.DATABASE['HOST'],
                                    settings.DATABASE['NAME'],
                                    settings.DATABASE['USER'],
                                    settings.DATABASE['PASSWORD'])
     bot = TwitchBot(name, conn, bot_db_logger, Queue.Queue(), self.log_filename)
     bot.daemon = True
     bot.connect_and_join_channels(channels)
     bot.start()
     return bot
def main():
    bot = TwitchBot()
    bot.run()
Exemple #10
0
"""Main file with Flask application and routes."""
import os
import json
import gettext
from signal import signal, SIGINT, SIGTERM, SIGABRT

from flask import Flask, request

from bot import TwitchBot
from twitch import TwitchApi

app = Flask(__name__)
bot = TwitchBot()
twitch_api = TwitchApi()

bot.register_twitch_api(twitch_api)
twitch_api.register_bot(bot)

gettext.install('pytwitchbot', os.path.join(os.path.dirname(__file__), 'po'))


def sig_handler(signum, frame):
    """Signal handler for manually stopping the bot."""
    bot.stop()
    os._exit(1)


for signum in (SIGINT, SIGTERM, SIGABRT):
    signal(signum, sig_handler)

Exemple #11
0
import threading

from apscheduler.schedulers.background import BackgroundScheduler

from bot import TwitchBot
from scheduler import SchedulerConfig
from tasks import data_mapper

try:
    sched = BackgroundScheduler(
        job_stores=SchedulerConfig.SCHEDULER_JOBSTORES,
        job_defaults=SchedulerConfig.SCHEDULER_JOB_DEFAULTS,
        executors=SchedulerConfig.SCHEDULER_EXECUTORS,
    )

    sched.start()
    threading.Thread(
        target=sched.add_job(
            data_mapper,
            trigger="interval",
            seconds=10,
            id="job_periodic",
            replace_existing=True,
        )
    ).start()

    bot = TwitchBot()
    threading.Thread(target=bot.run()).start()
except:
    print("Error: unable to start thread")
Exemple #12
0
from bot import TwitchBot, run, settings

run(
    TwitchBot(
        **{
            "command_prefix": ["twbeta ", "twb>"] if settings.
            UseBetaBot else ["twitch ", "Twitch ", "!twitch ", "tw>"],
            "owner_id":
            236251438685093889,
            "shard_count":
            40,
            "shard_ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        }))
Exemple #13
0
from bot import TwitchBot, run, settings
run(TwitchBot(**{
    "command_prefix": ["twbeta ", "twb>"] if settings.UseBetaBot else ["twitch ", "Twitch ", "!twitch ", "tw>"],
    "owner_id": 236251438685093889,
    "shard_count": 40,
    "shard_ids": [30,31,32,33,34,35,36,37,38,39]
}))
Exemple #14
0
from traceback import format_exception_only
from bot import TwitchBot
from config import DATA
from sys import exit
import logging

logFile, logLevel, *botData = DATA
logging.basicConfig(filename=logFile, filemode='w', level=logLevel, format='%(asctime)s %(levelname)s: %(message)s')

myBot = TwitchBot(*botData)

try:
    logging.debug('Starting bot...')
    myBot.run()
except(KeyboardInterrupt, SystemExit):
    logging.info('Received EXIT signal, exiting program...')
except Exception as e:
    logging.fatal(f'Program crashed: {" ".join(format_exception_only(type(e), e))}')
finally:
    logging.debug('Stopping bot...')
    exit()
Exemple #15
0
class TwitchPlays:
    __spot = None
    __bot = None
    __config = None
    __last_move = None
    __allow_movement = True

    def __init__(self):
        self.load_logging_configuration("INFO")
        self.__config = self.read_yaml()
        pass

    def activate_server(self):
        threading.Thread(
            target=Server(movement_callback=self.cb_movement,
                          stat_callback=self.cb_stats).start).start()

    def activate_bot(self):
        if self.__config is not None:
            self.__bot = TwitchBot("monstreytechnologies", None,
                                   self.__config.twitch_token,
                                   "monstreytechnologies", self.cb_movement)
            threading.Thread(target=self.__bot.start).start()
        else:
            logging.error("Invalid configuration")

    def activate_spot(self):
        if self.__config is not None:
            self.__spot = Spot(self.__config)

            def cb():
                threading.Thread(
                    target=self.__spot.image_helper.stream_images).start()
                self.__spot.enable_movement()

            threading.Thread(target=self.__spot.connect, args=[cb,
                                                               True]).start()
        else:
            logging.error("Invalid configuration")

    def cb_movement(self, move):
        if self.__spot is not None:
            if move == "pause":
                self.__allow_movement = False
            elif move == "resume":
                self.__allow_movement = True
            elif self.__allow_movement:
                self.__last_move = move
                return {
                    MOVEMENT_SIT: self.__spot.movement_helper.sit,
                    MOVEMENT_STAND: self.__spot.movement_helper.stand,
                    MOVEMENT_FORWARD: self.__spot.movement_helper.forward,
                    MOVEMENT_BACKWARD: self.__spot.movement_helper.backward,
                    MOVEMENT_TURN_LEFT:
                    self.__spot.movement_helper.rotate_left,
                    MOVEMENT_TURN_RIGHT:
                    self.__spot.movement_helper.rotate_right,
                    MOVEMENT_STRAFE_LEFT: self.__spot.movement_helper.left,
                    MOVEMENT_STRAFE_RIGHT: self.__spot.movement_helper.right
                }.get(move,
                      lambda: logging.error(f"Invalid move command: {move}"))()

        else:
            logging.error(
                f"Could not trigger {move} since Spot has not been initialised"
            )

    def cb_stats(self, stat):
        if stat == "battery" and self.__spot is not None:
            return {"stat": self.__spot.get_battery_level()}
        elif stat == "viewcount":
            return {"stat": self.__bot.get_chat_count()}
        elif stat == "lastcommand":
            return {"stat": self.__last_move}

    @staticmethod
    def load_logging_configuration(level):
        coloredlogs.install(
            level=level,
            fmt=
            '%(asctime)s.%(msecs)03d %(levelname)-8s %(filename)-20s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')

    @staticmethod
    def read_yaml():
        with open("assets/config.yaml", 'r') as stream:
            try:
                yaml_config = yaml.unsafe_load(stream)

                return Configuration(
                    host=yaml_config["connection"]["host"],
                    name=yaml_config["connection"]["name"],
                    guid=yaml_config["payload"]["guid"],
                    secret=yaml_config["payload"]["secret"],
                    twitch_token=yaml_config["twitch"]["token"])
            except yaml.YAMLError as err:
                logging.error(err)
                return None
Exemple #16
0
from bot import TwitchBot, run, settings
run(
    TwitchBot(
        **{
            "command_prefix": ["twbeta ", "twb>"] if settings.
            UseBetaBot else ["twitch ", "Twitch ", "!twitch ", "tw>"],
            "owner_id":
            236251438685093889,
            "shard_count":
            40,
            "shard_ids": [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
        }))