def twitch_followers(user): if refresh_twitch(user): try: if user.social_connection.twitch_connected: if user.social_connection.twitch_connected_mobile: client = TwitchClient(client_id=settings.TWITCH_ID_MOBILE, oauth_token=user.social_connection.twitch_token) else: client = TwitchClient(client_id=settings.TWITCH_ID, oauth_token=user.social_connection.twitch_token) channel = client.channels.get() return channel['followers'] except Exception as e: logger.debug("Token not valid") return 0 return 0
def parse(self, msg): lines = [] for word in msg['msg'].split(): username = None try: url = urlparse.urlparse(word) if 'twitch.tv' in url.netloc: username = url.path.split('/')[1] except: continue if not username: continue try: client = TwitchClient(client_id=self.config['twitch_client'], oauth_token=self.config['twitch_secret']) userid = client.users.translate_usernames_to_ids([username ])[0]['id'] livestreams = client.streams.get_live_streams([ userid, ]) if len(livestreams): ls = livestreams[0] ago = hms( int((pytz.timezone('US/Eastern').localize( datetime.datetime.now()) - pytz.utc.localize( ls['created_at'])).total_seconds())) lines.append( "TWITCH: {} is LIVE, playing {} with {} viewers (started {} ago)" .format(username, ls['game'], ls['viewers'], ago)) except: continue return lines
def follow_user(request, user_id): """ This function follows a streamer as long as the last follow event is older than the last unfollow event. """ user = request.user social = user.social_auth.get(provider='twitch') access_token = social.get_access_token(load_strategy()) client = TwitchClient(client_id='9hfygng7md3x7maw2g4uko0ednm3hk', oauth_token=access_token) last_follow = Event.objects.filter(user=user, streamer_id=user_id, event_type="Followed user").order_by('-id').first() last_unfollow = Event.objects.filter(user=user, streamer_id=user_id, event_type="Unfollowed user").order_by('-id').first() if last_follow: if last_unfollow: time1 = last_follow._meta.get_field('created_at').value_from_object(last_follow) time2 = last_unfollow._meta.get_field('created_at').value_from_object(last_unfollow) if (time1-time2).total_seconds() > 0: return(JsonResponse({"follows": "User was already following this channel"})) else: Event.objects.create(user=user, streamer_id=user_id, event_type="Followed user") return(JsonResponse({'follows': client.users.follow_channel(social.uid, user_id)})) return(JsonResponse({"follows": "User was already following this channel"})) Event.objects.create(user=user, streamer_id=user_id, event_type="Followed user") return(JsonResponse({'follows': client.users.follow_channel(social.uid, user_id)}))
def unfollow_user(request, user_id): """ This function unfollows a user as long as the last follow event is more recent than the last unfollow event. """ user = request.user social = user.social_auth.get(provider='twitch') client = TwitchClient(client_id='9hfygng7md3x7maw2g4uko0ednm3hk', oauth_token=social.extra_data['access_token']) last_follow = Event.objects.filter(user=user, streamer_id=user_id, event_type="Followed user").order_by('-id').first() last_unfollow = Event.objects.filter(user=user, streamer_id=user_id, event_type="Unfollowed user").order_by('-id').first() if not last_follow: return(JsonResponse({"response:" "User was not following this channel"})) if last_follow: if last_unfollow: time1 = last_follow._meta.get_field('created_at').value_from_object(last_follow) time2 = last_unfollow._meta.get_field('created_at').value_from_object(last_unfollow) if (time1-time2).total_seconds() > 0: Event.objects.create(user=user, streamer_id=user_id, event_type="Unfollowed user") client.users.unfollow_channel(social.uid, user_id) return(JsonResponse({"response": "User succesfully unfollowed"})) else: return(JsonResponse({"response": "User was not following this channel"})) Event.objects.create(user=user, streamer_id=user_id, event_type="Unfollowed user") client.users.unfollow_channel(social.uid, user_id) return JsonResponse({'response': "User succesfully unfollowed"})
async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
def get_account_info(self): result = {} path_parts = self.account_link.path.strip('/').split('/') account_login = path_parts[-1] if account_login is None: return result try: client = TwitchClient( client_id=settings.SOCIAL_NETWORK_TWITCH_CLIENT_ID, oauth_token=settings.SOCIAL_NETWORK_TWITCH_TOKEN) users = client.users.translate_usernames_to_ids(account_login) if users: user_info = users[-1] result['logo'] = user_info['logo'] result['title'] = user_info['display_name'] except Exception as e: logger.exception(e) return result
def __init__(self, bot): self.bot = bot self.messages = [] self.client = TwitchClient(client_id=environ['twitch_key']) #create background tasks self.bot.loop.create_task(self.turn_off_buttons())
def check_user(user): global CLIENT_ID global VALID_BROADCAST """ returns 0: online, 1: offline, 2: not found, 3: error """ try: client = TwitchClient(client_id=CLIENT_ID) response = client.users.translate_usernames_to_ids(user) except reqexc.HTTPError as ex: print("Bad client id: '%s'" %(CLIENT_ID)) print(ex) get_client_id() sys.exit(4) stream_info = 0 if response.__len__() > 0: user_id = response[0].id stream_info = client.streams.get_stream_by_user(user_id) if stream_info is not None: if stream_info.broadcast_platform in VALID_BROADCAST: status = 0 # user is streaming else: status = 3 # unexpected error else: status = 1 # user offline else: status = 2 # user not found return status, stream_info
def get_client(): try: client = TwitchClient(client_id()) logger.info("Twitch client connection successful") return client except Exception as e: logger.error("Twitch client connection unsuccessful", exc_info=True)
async def main(): try: conf.load() except FileNotFoundError as e: logger.error(f"Configuration file not found: {e.filename}") logger.warn("Writing default settings file...") default_settings = pkg_resources.read_text(zeatbot.data, "settings.ini") Path(e.filename).parent.mkdir(parents=True, exist_ok=True) with open(e.filename, "w") as f: f.write(default_settings) logger.info("Please reload the bot.") return irc = IRC(oauth=conf.oauth, streamername=conf.streamername, botname=conf.botname, displayname=conf.displayname) await irc.connect() await irc.sendmsg("I'm online!") logger.info( f"Connected to IRC channel #{conf.streamername} as {conf.botname}.") client = TwitchClient(client_id=conf.clientid, oauth_token=conf.oauth) (zeatuser, ) = client.users.translate_usernames_to_ids([conf.streamername]) channel = client.channels.get_by_id(zeatuser.id) asyncio.create_task(timers.loop(irc)) while True: message = await irc.readmsg() logger.info(message) if (message.command == "PING"): await irc.pong() elif (message.command == "PRIVMSG"): asyncio.create_task(on_message(irc, client, channel, message))
def __init__(self, twitch_api_key, sql_user, sql_pass, sql_host, sql_database): self.key = twitch_api_key self.client = TwitchClient(client_id=twitch_api_key) self.http = urllib3.PoolManager() self.sql_connector = mysql.connector.connect(user=sql_user, password=sql_pass, host=sql_host, database=sql_database) runs = 24 current_minutes = datetime.datetime.now().minute if current_minutes != 0: sleep_time = (60 - current_minutes) * 60 print("Sleeping for an flat hour: " + str(sleep_time) + " seconds") time.sleep(sleep_time) while runs > 0: print("This many runs left: " + str(runs)) start = datetime.datetime.now() games = self.client.games.get_top(limit=50) for game in games: self.run_query(game) wait_time = (datetime.datetime.now() - start).seconds print("Waiting this long before starting the next run: " + str(3600 - wait_time)) runs -= 1 time.sleep(3600 - wait_time)
def main(): # initialize the Reddit instance reddit = praw.Reddit('bot1') subreddit = reddit.subreddit("AwkwardSinceBirth") # get the status of AwkwardSinceBirth stream client = TwitchClient(client_id='x1vq30gh1w0pxqearh5l741m6p8ns2') stream = client.streams.get_live_streams(channel='130594176') # Channel is fixed to AwkwardSinceBirth's ID currently_streaming = len(stream) > 0 post_title = 'Alex is currently streaming on Twitch!' # Search the subreddit (by new) for a post with the above title. If it exists, save the ID and exit the loop. for submission in subreddit.new(): post_exists = submission.title == post_title if post_exists: post_id = submission.id break # If the post exists and he is not streaming, delete the post. # If it doesn't exist and he is streaming, create the post. Pass over in all other cases. if post_exists: if currently_streaming: pass else: reddit.submission(post_id).delete() print("Deleted a post") else: if currently_streaming: submission = subreddit.submit(title=post_title, url='twitch.tv/AwkwardSinceBirth') # submission.mod.distinguish(how='yes', sticky=True) print("made a post") else: pass
def get_active_channel(limit=2): bots = TwitchClient(client_id=config.channel_client_id) stream = bots.streams.get_live_streams(limit=100) # channel_list = [item[u'channel'][u'display_name'].encode('ascii','ignore').lower() for item in stream] print("connecting to channels:{}".format(channel_list[0:2])) return channel_list[0:limit]
def fill_viewer_list(schema): client = TwitchClient(cfg.ClientID) while True: for event in obs.get_events(): if event.type == 'TWITCHCHATMESSAGE': try: conn = db.connect(dbname=cfg.DBname, user=cfg.DBuser, password=cfg.DBpassword, host=cfg.DBhost, port=cfg.DBport) conn.autocommit = True viewer = str(event.nickname) viewerID = client.users.translate_usernames_to_ids( event.nickname) viewerID = str(viewerID) viewerID = viewerID.split(",") viewerID = viewerID[1] viewerID = viewerID.split(":") viewerID = viewerID[1] viewerID = viewerID.split("'") viewerID = int(viewerID[1]) joindate = str(time.strftime("%Y.%m.%d")) points = int(0) # insert data in table cursor = conn.cursor() query = """INSERT INTO {0}.viewerlist ( viewer, viewerID, joindate, points ) Values( %(viewer)s, %(viewerID)s, %(joindate)s, %(points)s ) on CONFLICT (viewerID) DO NOTHING """.format(schema) cursor.execute( query, { 'viewer': viewer, 'viewerID': viewerID, 'joindate': joindate, 'points': points }) cursor.close() conn.close except: print("error")
def __init__(self, *args): super().__init__(*args) self.helix = TwitchHelix( client_id='vnsbdjciw4fcif1k57w1c07a65wk03', oauth_token='oauth:17qyf4koyvfdqjs4me7zr451lccmtn') self.client = TwitchClient( client_id='vnsbdjciw4fcif1k57w1c07a65wk03', oauth_token='oauth:17qyf4koyvfdqjs4me7zr451lccmtn')
def printTwitchIDs(): client = TwitchClient(client_id='hfwl010tvr2r6s4cp9xgx9um5zvftf') channel = client.channels.get_videos(119136051, 100, 0, 'archive') for val in channel: if (val.id[0] == 'v'): val.id = val.id[1:] print(val.id)
def main(self): # Configure logging module logging.basicConfig(filename='recorder.log', format='%(asctime)s %(message)s', filemode='a', level=logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logging.getLogger().addHandler(handler) logging.info("Twitch Recorder startup requested") logging.getLogger('googleapiclient.discovery_cache').setLevel( logging.ERROR) # Mute discovery warning, it's working baby logging.getLogger('streamlink.stream.hls').setLevel( logging.ERROR ) # TODO: Mute Failed to reload playlist, I don't have idea deal with it. logging.debug("Check Twitch API") f = open('twitch.token', 'r') clientId = f.readline() oAuthToken = "" if (f.readable()): oAuthToken = f.readline() f.close() self.client = TwitchClient(client_id=clientId, oauth_token=oAuthToken) logging.debug("Check Twitch Token") if os.path.exists('twitch_access.token'): f = open('twitch_access.token', 'r') self.accessToken = f.readline() f.close() logging.debug("Check Google Drive API") gauth = GoogleAuth() gauth.settings['get_refresh_token'] = True # Create local webserver and auto handles authentication. gauth.LoadCredentialsFile("token.key") if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("token.key") self.refreshFetchList(True) logging.info( "{} streamers registered for record, start TwitchRecorder-GoogleDrive" .format(len(self.checkers))) self.update()
def __init__(self, bot): self.bot = bot self.channels = [] self.active_streams = [] self.notification_reciever = None self.twitch = TwitchClient(client_id=config.twitch_client_id) self.poll_channels.start()
def get_active_channel(offset=0, limit=100): bots = TwitchClient(client_id=config.channel_client_id) stream = bots.streams.get_live_streams(offset=offset, limit=limit) channel_list = [ item[u'channel'][u'name'].encode('ascii', 'ignore').lower() for item in stream ] return channel_list
def getTwitchAPIAccess(): home = str(Path.home()) home = home + '/.tw' cid = open(home) twID = cid.read() twitch = TwitchClient(twID) return twitch
def test_client_reads_credentials_from_file(monkeypatch): def mockreturn(path): return "tests/api/dummy_credentials.cfg" monkeypatch.setattr(os.path, "expanduser", mockreturn) c = TwitchClient() assert c._client_id == "spongebob" assert c._oauth_token == "squarepants"
def __init__(self, bot): self.bot = bot self.connection = sqlite3.connect(DATABASE) self.c = self.connection.cursor() self.twitchClient = TwitchClient(client_id=TWITCH_ID) self.notifier_task = bot.loop.create_task(self.twitch_notify()) self.notifier_task_lock = asyncio.Lock()
async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False
def __init__(self): self.conf = self.init_parser() client_id = self.conf.client_id self.client = TwitchClient(client_id=client_id) self.video_url_base = "https://www.twitch.tv/videos/" self.api_base = "https://api.twitch.tv/kraken/" self.headers = { "Accept": "application/vnd.twitchtv.v5+json", "Client-ID": client_id, }
def get_channels_for_users(usernames): client = TwitchClient(client_id=twitch_client_id) all_channels = [] batches = chunks(usernames, 50) for batch in batches: channels = client.users.translate_usernames_to_ids(batch) all_channels.extend(channels) return all_channels
def getClipsByChannel(channels): client = TwitchClient(client_id=DAVID_API_KEY) for channel in channels: client.clips.get_top(channel=channel, game=GAME, limit=ClIP_NUMBER, period=PERIOD) client.clips.get_top(channel=channel, game=GAME, limit=ClIP_NUMBER, period=PERIOD)
def __init__(self, config): self.config = config self.log = logging.getLogger() # setup cassandra below self.cass = PythonCassandraExample(self.config) self.cass.createsession() self.cass.setlogger() self.cass.session.set_keyspace(self.config['cassandra_keyspace']) self.client = TwitchClient(client_id=self.config['client_id']) self.redis = redis.Redis(host=self.config['redis_host'], port=6379)
def update_twitch(): """Update twitch. Broken until client lib switches to new API.""" # Set up twitch posts twitch_client = TwitchClient( client_id=os.getenv("TWITCH_CLIENT_ID"), oauth_token=os.getenv("TWITCH_OAUTH")) channel_info = twitch_client.channels.get() channel_id = channel_info.id logger.debug(channel_id) # Get existing updates posts = twitch_client.channel_feed.get_posts( channel_id=channel_id, comments=None)
def users_metadata(users): #print len(users) #print users username = "******" client_id = "ykvnzoa5e28awecbj52yiva0f6dgme" token = "cpecc5vo2jeb7ag5zsauchvggrk2rl" client = TwitchClient(client_id=client_id, oauth_token=token) users_info = [] for i in range(0, len(users), 50): print "i value:" + str(i) print "users chunk len:" + str(len(users[i:i + 50])) temp = client.users.translate_usernames_to_ids(users[i:i + 50]) print "len of temp:" + str(len(temp)) users_info = users_info + temp print len(users_info) time.sleep(1) user_app = [] for user in users_info: print '{} : {}'.format(user.name, user.id) user_app.append(user.name) for user in users: if user not in user_app: print user features = np.empty([len(users), 3]) for i in range(len(users_info)): url = 'https://api.twitch.tv/helix/users/follows?to_id=' + str( users_info[i].id) headers = {'Client-ID': 'ykvnzoa5e28awecbj52yiva0f6dgme'} req = urllib2.Request(url, headers=headers) response = urllib2.urlopen(req) respData = json.loads(response.read()) features[i][1] = respData['total'] #No of users following the user url = 'https://api.twitch.tv/helix/users/follows?from_id=' + str( users_info[i].id) req = urllib2.Request(url, headers=headers) response = urllib2.urlopen(req) respData = json.loads(response.read()) features[i][0] = respData[ 'total'] #No of Users being followed by the user headers = { 'Accept': 'application/vnd.twitchtv.v5+json', 'Client-ID': 'ykvnzoa5e28awecbj52yiva0f6dgme' } url = 'https://api.twitch.tv/kraken/users/' + str( users_info[i].id) + '/follows/channels' req = urllib2.Request(url, headers=headers) response = urllib2.urlopen(req) respData = json.loads(response.read()) features[i][2] = respData[ '_total'] # No of channels been followed by user time.sleep(10) return features
def __init__(self, bot): self.bot = bot self.sended_messages = [] self.update_messages = [] self.follows = [] self.client = TwitchClient( client_id= environ['twitch_key'] ) #create background tasks self.bot.loop.create_task(self.stream_notification()) self.bot.loop.create_task(self.recreate_message()) self.bot.loop.create_task(self.turn_off_buttons())
class CommonNetworkTwitchV5(object): """ Class for interfacing with TwitchTV V5 api """ def __init__(self, option_config_json): self.twitch_inst = TwitchClient(client_id=option_config_json['Twitch']['ClientID'], oauth_token=option_config_json['Twitch']['OAuth']) # chat def com_net_twitch_chat_badges(self, channel_id): return self.twitch_inst.get_badges_by_channel(channel_id) def com_net_twitch_chat_emoticons(self): return self.twitch_inst.get_all_emoticons() # channel feed # channels def com_net_twitch_channels_by_id(self, channel_id): """ Gets a specified channel object. Parameters: channel_id (string) - Channel ID """ return self.twitch_inst.channels.get_by_id(channel_id) # clips def com_net_twitch_clip_by_slug(self, slug_id): """ Gets a clip object based on the slug provided Parameters: slug (string) - Twitch Slug. """ return self.twitch_inst.clips.get_by_slug(slug_id) def com_net_twitch_top_channels(self, channel, cursor, game, language, limit, period, trending): """ channel (string) – Channel name. If this is specified, top clips for only this channel are returned; otherwise, top clips for all channels are returned. If both channel and game are specified, game is ignored. cursor (string) – Tells the server where to start fetching the next set of results, in a multi-page response. game (string) – Game name. (Game names can be retrieved with the Search Games endpoint.) If this is specified, top clips for only this game are returned; otherwise, top clips for all games are returned. If both channel and game are specified, game is ignored. language (string) – Comma-separated list of languages, which constrains the languages of videos returned. Examples: es, en,es,th. If no language is specified, all languages are returned. limit (int) – Maximum number of most-recent objects to return. Default: 10. Maximum: 100. period (string) – The window of time to search for clips. Valid values: day, week, month, all. Default: week. trending (boolean) – If True, the clips returned are ordered by popularity; otherwise, by viewcount. Default: False. """ return self.twitch_inst.get_top() def com_net_twitch_followed(self, limit, cursor, trending): """ limit (int) – Maximum number of most-recent objects to return. Default: 10. Maximum: 100. cursor (string) – Tells the server where to start fetching the next set of results, in a multi-page response. trending (boolean) – If true, the clips returned are ordered by popularity; otherwise, by viewcount. Default: false. """ return self.twitch_inst.followed() # communities # collections # games # ingests # search # streams def com_net_twitch_get_featured(self, limit=100, offset=0): return self.twitch_inst.get_featured(limit, offset)
def __init__(self, option_config_json): self.twitch_inst = TwitchClient(client_id=option_config_json['Twitch']['ClientID'], oauth_token=option_config_json['Twitch']['OAuth'])