def main(): AsyncIOMainLoop().install() loop = asyncio.get_event_loop() async_twitch = AsyncTwitchWrapper( loop, Twitch( config['RING_BUFFER_SIZE'] * 1024 * 1024, config['STREAM_RESOLUTION'], config['TWITCH_OAUTH'], config['TWITCH_CHANNEL'] ) ) async_twitch.initialize() asyncio.Task(pereodic_stream_updates(async_twitch, 10)) uploader = AsyncUploaderWrapper( loop, uploader=resolve_uploader() ) app = application(async_twitch, uploader) app.listen(config['PORT']) print('Listening port {port}...'.format(port=config['PORT'])) loop.run_forever()
def execute(self): """ This function will eventually call a chron to go on twitch and create/dl clips when the 'time is right' """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((twitch_cfg['HOST'], twitch_cfg['PORT'])) s.send(("PASS " + twitch_cfg['PASS'] + "\r\n").encode()) s.send(("NICK " + twitch_cfg['IDENT'] + "\r\n").encode()) s.send(("JOIN " + '#adren_tv' + "\r\n").encode()) read_join_greeting(s) readbuffer = "" t = Twitch() num_viewers = t.get_viewers('adren_tv') while True: readbuffer += str(s.recv(1024), 'utf-8') temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: print(line) if "PING" in line: s.send(line.replace("PING", "PONG").encode('utf-8')) break
def __init__(self, username): config = ConfigParser.ConfigParser() config.read('./config.properties') self.pinterest = Pinterest(username, config) self.googleplus = GooglePlus(username, config) self.youtube = YouTube(username, config) self.twitch = Twitch(username, config) self.vimeo = Vimeo(username, config) self.behance = Behance(username, config) self.instagram = Instagram(username, config) self.twitter = Twitter(username, config) self.github = Github(username, config) self.dict = dict()
def __init__(self): threading.Thread.__init__(self) self.running = True self.settings = self.load_config() self.slack = SlackClient(self.settings.get('chat_token')) self.bot = SlackClient(self.settings.get('bot_token')) twitch = Twitch(self) self.commands = [ UseChannel(self, self.bot), SetIdentity(self, self.bot), Ping(self, self.bot), TwitchManager(self, self.bot, twitch), ] self.context = None self.announce()
async def main(): if "youtube.com/channel" in sys.argv[1] or "youtube.com/watch" in sys.argv[ 1]: s = Youtube(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") data = await s.get_play_info() title = data["title"] url = data["play_url"] elif "twitch.tv/" in sys.argv[1]: s = Twitch(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") data = await s.get_play_info() title = data["title"] url = data["play_url"] elif "douyu.com/" in sys.argv[1]: s = Douyu(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") data = await s.get_play_info() title = data["title"] url = data["play_url"] elif "huya.com/" in sys.argv[1]: s = Huya(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") data = await s.get_play_info() title = data["title"] url = data["play_url"] elif "live.bilibili.com/" in sys.argv[1]: s = Bilibili(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") data = await s.get_play_info() title = data["title"] url = data["play_url"] elif "bilibili.com/" in sys.argv[1]: s = Bilibili(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "") await s.get_play_info_video() return else: await run_ykdl(sys.argv[1]) return print("title: " + title, flush=True) print(url, flush=True)
import env from flask import Flask from flask import redirect from flask import render_template from flask import request from twitch import Twitch trueStrings = [">", "y", "Y"] falseStrings = ["<", "n", "N"] app = Flask(__name__) t = Twitch() t.twitch_connect(env.TWITCH_USERNAME, env.TWITCH_KEY) @app.route("/") def getIndex(): return render_template("index.html") @app.route("/twitch") def getTwitch(): messages = t.twitch_recieve_messages() trues, falses = 0, 0 if messages: for message in messages:
return redirect('/') @app.route('/form/delete', methods=['POST']) def delete_form(): requests.delete('http://127.0.0.1:5000/api/custom', headers={ 'Content-Type': 'application/json', 'accept': 'application/json' }, data="{ \"channel\": \"" + request.form['channel'] + "\"}") return redirect('/') if __name__ == "__main__": twitch = Twitch() twitch.add_stream_by_id("31239503") twitch.streams['ESL_CSGO']['static'] = True twitch.streams['ESL_CSGO']['display_name'] = "ESL" twitch.streams['ESL_CSGO']['banner'] = '/static/images/esl_logo.png' twitch.add_stream("dreamhackcs") twitch.streams['dreamhackcs']['static'] = True twitch.streams['dreamhackcs']['display_name'] = "Dreamhack" twitch.streams['dreamhackcs'][ 'banner'] = '/static/images/dreamhack_logo.png' lq = Liquipedia() app.run(debug=True)
def run(self): font_dir = "{}/../../../fonts/".format( os.path.dirname(os.path.realpath(__file__))) config_filename = "{}/config.ini".format( os.path.dirname(os.path.realpath(__file__))) config = configparser.ConfigParser() config.read(config_filename) check_interval = config.getint('settings', 'check-interval') brightness = config.getint('settings', 'brightness') show_offline_clock = config.getboolean('settings', 'show-offline-clock') client_id = config['twitch']['client-id'] client_bearer = config.get('twitch', 'bearer', fallback=None) client_secret = config.get('twitch', 'secret', fallback=None) if client_bearer is None and client_secret is None: raise Exception( "If no bearer token is provided, an API secret key is needed to retrieve a bearer token." ) streamer = config.get('twitch', 'streamer') twitch = Twitch(client_id, bearer=client_bearer) if client_bearer is None: # get a new bearer token and save it to file. The twitch class automatically stores this locally client_bearer = twitch.get_bearer(client_secret) config.set('twitch', 'bearer', client_bearer) with open(config_filename, 'w') as configfile: config.write(configfile) offscreen_canvas = self.matrix.CreateFrameCanvas() font = graphics.Font() font.LoadFont("{}4x6.bdf".format(font_dir)) font_large = graphics.Font() font_large.LoadFont("{}7x13.bdf".format(font_dir)) font_medium = graphics.Font() font_medium.LoadFont("{}6x13.bdf".format(font_dir)) textColor = graphics.Color(255, 255, 0) pos = offscreen_canvas.width feed_check_time = 0 while True: if time.time() - feed_check_time >= check_interval: stream_info = twitch.get_stream_info(streamer) feed_check_time = time.time() is_online = stream_info['is_live'] offscreen_canvas.Clear() if is_online: offscreen_canvas.brightness = brightness textColor = graphics.Color(0, 255, 0) game_name = stream_info['game_name'] stream_start = stream_info['started_at'] stream_duration = datetime.datetime.utcnow( ) - datetime.datetime.strptime(stream_start, "%Y-%m-%dT%H:%M:%SZ") if game_name == "Just Chatting": game_name = "Just Stalling" len = graphics.DrawText(offscreen_canvas, font_large, pos, 14, textColor, game_name) pos = pos - 1 if pos + len <= 0: pos = offscreen_canvas.width graphics.DrawText(offscreen_canvas, font, 3, 5, graphics.Color(127, 127, 255), str(stream_duration)) offsecreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas) time.sleep(0.05) else: offscreen_canvas.brightness = 50 textColor = graphics.Color(255, 0, 0) graphics.DrawText(offscreen_canvas, font, 2, 6, textColor, "OFFLINE") if show_offline_clock: current_datetime = datetime.datetime.now() graphics.DrawText(offscreen_canvas, font_medium, 2, 16, graphics.Color(0, 127, 0), current_datetime.strftime("%H:%M")) offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas) time.sleep(1)
def procCommand(self): if self.command == 'getlb': msrcom = srcom.srcom() self.output = msrcom.get_lb(' '.join(map(str,self.parms))) return True elif self.command == 'title': global channel mtwitch = Twitch() mtwitch.title(' '.join(map(str, self.parms))) return True elif self.command == 'game': global channel mtwitch = Twitch() mtwitch.game(' '.join(map(str, self.parms))) return True elif self.command == 'hi': self.output = 'Hello ' + self.user + '!' return True elif self.command == 'bye': self.killCommand = True self.output = 'Bye, love you!' return True elif self.command == 'fact': mSql = SQL.SQL() if not self.parms: fact = mSql.selectAsArray("SELECT * FROM facts ORDER BY RAND()LIMIT 0,1;", None) self.output = fact elif self.parms[0] == "add": ddb = DynamoDB(globals.channel.user_id) # TODO fact text is storing with quotes, need to strip them off ddb.put_fact(self.parms[1], self.parms[2]) self.command = 'fact' self.parms = {self.parms[1]} self.procCommand() else: ddb = DynamoDB(globals.channel.user_id) fact = ddb.get_fact(self.parms[0]) if not fact: self.output = "Sorry buddy, fact not found. :(" else: self.output = fact return True else: return True
async def init_state(app): # We have to put "kill" into a dict to prevent getting: # DeprecationWarning: Changing state of started or joined application is deprecated app["data"] = {"kill": False} app["date"] = {"startedAt": datetime.now(timezone.utc)} if "db" not in app: app["db"] = None app["users"] = { "Random-Mover": User(app, bot=True, username="******"), "Fairy-Stockfish": User(app, bot=True, username="******"), "Discord-Relay": User(app, anon=True, username="******"), } app["users"]["Random-Mover"].online = True app["lobbysockets"] = { } # one dict only! {user.username: user.tournament_sockets, ...} app["lobbychat"] = collections.deque([], MAX_CHAT_LINES) app["tourneysockets"] = { } # one dict per tournament! {tournamentId: {user.username: user.tournament_sockets, ...}, ...} app["tourneynames"] = { } # cache for profile game list page {tournamentId: tournament.name, ...} app["tournaments"] = {} app["tourneychat"] = { } # one deque per tournament! {tournamentId: collections.deque([], MAX_CHAT_LINES), ...} app["seeks"] = {} app["games"] = {} app["invites"] = {} app["game_channels"] = set() app["invite_channels"] = set() app["highscore"] = {variant: ValueSortedDict(neg) for variant in VARIANTS} app["crosstable"] = {} app["shield"] = {} app["shield_owners"] = {} # {variant: username, ...} app["stats"] = {} app["stats_humans"] = {} # counters for games app["g_cnt"] = [0] # last game played app["tv"] = None app["twitch"] = Twitch(app) if not DEV: await app["twitch"].init_subscriptions() # fishnet active workers app["workers"] = set() # fishnet works app["works"] = {} # fishnet worker tasks app["fishnet"] = asyncio.PriorityQueue() # fishnet workers monitor app["fishnet_monitor"] = {} app["fishnet_versions"] = {} for key in FISHNET_KEYS: app["fishnet_monitor"][FISHNET_KEYS[key]] = collections.deque([], 50) rm = app["users"]["Random-Mover"] ai = app["users"]["Fairy-Stockfish"] asyncio.create_task(BOT_task(ai, app)) asyncio.create_task(BOT_task(rm, app)) # Configure templating. app["jinja"] = {} base = os.path.dirname(__file__) for lang in LANGUAGES: # Generate compiled mo file folder = os.path.join(base, "../lang/", lang, "LC_MESSAGES") poname = os.path.join(folder, "server.po") moname = os.path.join(folder, "server.mo") try: with open(poname, 'rb') as po_file: po_lines = [ line for line in po_file if line[:8] != b"#, fuzzy" ] mo = Msgfmt(po_lines).get() with open(moname, 'wb') as mo_file: mo_file.write(mo) except PoSyntaxError: log.error("PoSyntaxError in %s", poname) # Create translation class try: translation = gettext.translation("server", localedir="lang", languages=[lang]) except FileNotFoundError: log.warning("Missing translations file for lang %s", lang) translation = gettext.NullTranslations() env = jinja2.Environment(enable_async=True, extensions=['jinja2.ext.i18n'], loader=jinja2.FileSystemLoader("templates"), autoescape=jinja2.select_autoescape(["html"])) env.install_gettext_translations(translation, newstyle=True) env.globals["static"] = static_url app["jinja"][lang] = env if app["db"] is None: return # Read tournaments, users and highscore from db try: cursor = app["db"].user.find() async for doc in cursor: if doc["_id"] not in app["users"]: perfs = doc.get("perfs") if perfs is None: perfs = {variant: DEFAULT_PERF for variant in VARIANTS} app["users"][doc["_id"]] = User(app, username=doc["_id"], title=doc.get("title"), bot=doc.get("title") == "BOT", perfs=perfs, enabled=doc.get( "enabled", True)) cursor = app["db"].tournament.find() cursor.sort('startsAt', -1) counter = 0 async for doc in cursor: if doc["status"] in (T_CREATED, T_STARTED): await load_tournament(app, doc["_id"]) counter += 1 if counter > 3: break await generate_shield(app) db_collections = await app["db"].list_collection_names() # if "highscore" not in db_collections: # Always create new highscore lists on server start await generate_highscore(app["db"]) cursor = app["db"].highscore.find() async for doc in cursor: app["highscore"][doc["_id"]] = ValueSortedDict(neg, doc["scores"]) if "crosstable" not in db_collections: await generate_crosstable(app["db"]) cursor = app["db"].crosstable.find() async for doc in cursor: app["crosstable"][doc["_id"]] = doc await app["db"].game.create_index("us") await app["db"].game.create_index("v") await app["db"].game.create_index("y") await app["db"].game.create_index("by") except Exception: print("Maybe mongodb is not running...") raise # create test tournament if 1: pass
from twitch import Twitch CID = "дÉÏTÕ¾µÄclientID" if __name__ == "__main__": t = Twitch(CID) t.reprint_force(437097337, False)