def __init__(self, twitch_appid, twitch_secret, callback_url): self.discord_username = "******" self.twitch = Twitch(twitch_appid, twitch_secret) self.callback_url = callback_url self.hook = TwitchWebHook(callback_url, twitch_appid, 8080) self.authenticated = False self.subscriptions = []
def __init__(self): super().__init__() self.credential: credentials.Twitch_Credential() self.twitch: Twitch() self.target_scope = [ AuthScope.WHISPERS_READ, AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.BITS_READ, AuthScope.CHANNEL_READ_SUBSCRIPTIONS ]
def getTwitchInformation(): twitchAppId = getConfigInformationAsString("TwitchAPI", "TwitchAppId") twitchAppSecret = getConfigInformationAsString("TwitchAPI", "TwitchAppSecret") broadcasterId = getConfigInformationAsString("TwitchAPI", "TwitchBoradcastId") twitch = Twitch(twitchAppId, twitchAppSecret) twitch.authenticate_app([]) return twitch.get_channel_information(broadcasterId)
def __init__(self, TWITCH_APP_ID, TWITCH_SECRET, User, isID = False): self.reader = codecs.getreader('utf-8') self.TWITCH_APP_ID = TWITCH_APP_ID self.TWITCH_SECRET = TWITCH_SECRET self.twitch = Twitch(self.TWITCH_APP_ID, self.TWITCH_SECRET) self.StreamerName = User self.isID = isID self.LOCK = False if not self.isID: self.StreamerID = self.getUserID()
def _twitch_init_(self): self.bot.logger.info("Registering with Twitch...") self.twitch = Twitch(self.config['id'], self.config['secret']) self.twitch.authenticate_app([]) self.bot.logger.info( f"Registering webhook endpoint {self.config['myurl']} ...") self.hook = TwitchWebHook(self.config['myurl'], self.config['id'], self.config['port'], ssl_context=self.sslcontext) self.hook.authenticate(self.twitch) self.bot.logger.info("Clearing all hook subscriptions...") self.hook.unsubscribe_all(self.twitch) # Clear all subs on startup self.hook.start() self._register_all()
def start(bot): target_scope = [ AuthScope.ANALYTICS_READ_GAMES, AuthScope.BITS_READ, AuthScope.CHANNEL_EDIT_COMMERCIAL, AuthScope.CHANNEL_MANAGE_BROADCAST, AuthScope.CHANNEL_MANAGE_POLLS, AuthScope.CHANNEL_MANAGE_PREDICTIONS, AuthScope.CHANNEL_MANAGE_REDEMPTIONS, AuthScope.CHANNEL_MODERATE, AuthScope.CHANNEL_READ_HYPE_TRAIN, AuthScope.CHANNEL_READ_POLLS, AuthScope.CHANNEL_READ_PREDICTIONS, AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.CHANNEL_READ_SUBSCRIPTIONS, AuthScope.CHANNEL_SUBSCRIPTIONS, AuthScope.CHAT_EDIT, AuthScope.CHAT_READ, AuthScope.CLIPS_EDIT, AuthScope.MODERATION_READ, AuthScope.USER_EDIT_BROADCAST, AuthScope.USER_MANAGE_BLOCKED_USERS, AuthScope.USER_READ_BLOCKED_USERS, AuthScope.USER_READ_BROADCAST, AuthScope.USER_READ_FOLLOWS, AuthScope.USER_READ_SUBSCRIPTIONS ] twitch = Twitch(config['client_id'], config['client_secret']) twitch.authenticate_app([]) twitch.set_user_authentication(config['twitch_token'], target_scope, config['refresh_token']) def callback_bits(uuid: UUID, data: dict): print(f"Got callback for UUID {str(uuid)}") print(data) pubsub.bits(bot, data['data']) def callback_subscriptions(uuid: UUID, data: dict): print(f"Got callback for UUID {str(uuid)}") print(data) pubsub.subscription(bot, data['data']) def callback_points(uuid: UUID, data: dict): print(f"Got callback for UUID {str(uuid)}") print(data) pubsub.points(bot, data['data']) user_id = twitch.get_users(logins=['will_am_i_'])['data'][0]['id'] pubsubs = PubSub(twitch) pubsubs.start() bits_uuid = pubsubs.listen_bits(user_id, callback_bits) subscriptions_uuid = pubsubs.listen_channel_subscriptions( user_id, callback_subscriptions) points_uuid = pubsubs.listen_channel_points(user_id, callback_points) #pubsubs.stop()
def __init__(self): super().__init__() self.credential: credentials.Twitch_Credential() self.twitch: Twitch() self.pubsub: PubSub() self.target_scope = [ AuthScope.WHISPERS_READ, AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.BITS_READ, AuthScope.CHANNEL_READ_SUBSCRIPTIONS ] self.uuid_whisper = None self.uuid_channelPoints = None self.uuid_bits = None self.uuid_subs = None self.cooldownModule: Cooldown_Module = Cooldown_Module() self.cooldownModule.setupCooldown("twitchpubsub", 20, 32)
def __init__(self): self.cfg = configs() self.CLIENT_ID = self.cfg.get_client_id() self.CLIENT_SECRET = self.cfg.get_client_secret() self.twitch = Twitch(self.get_client_id(), self.get_client_secret()) self.OAUTH_TOKEN = self.twitch.get_app_token() self.HEADERS = { 'Client-ID': self.get_client_id(), 'Authorization': f'Bearer {self.get_oauth_token()}' } self.LIVE = True self.OFFLINE = False self.LIVE_CHANNEL_ID = self.cfg.get_live_channel_id() self.streamer_list = self.cfg.get_streamer_list()
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Twitch platform.""" channels = config[CONF_CHANNELS] client_id = config[CONF_CLIENT_ID] client_secret = config[CONF_CLIENT_SECRET] oauth_token = config.get(CONF_TOKEN) try: client = Twitch( app_id=client_id, app_secret=client_secret, target_app_auth_scope=OAUTH_SCOPES, ) client.auto_refresh_auth = False except TwitchAuthorizationException: _LOGGER.error("Invalid client ID or client secret") return if oauth_token: try: client.set_user_authentication(token=oauth_token, scope=OAUTH_SCOPES, validate=True) except MissingScopeException: _LOGGER.error("OAuth token is missing required scope") return except InvalidTokenException: _LOGGER.error("OAuth token is invalid") return channels = client.get_users(logins=channels) add_entities( [TwitchSensor(channel, client) for channel in channels["data"]], True, )
def __init__(self, bot): self.bot = bot self.client_id = os.getenv('TWITCH_CLIENT_ID') self.client_secret = os.getenv('TWITCH_SECRET') self.twitch = Twitch(self.client_id, self.client_secret) self.conn = psycopg2.connect(user=os.getenv("PGUSER"), password=os.getenv("PGPASSWORD"), host=os.getenv("PGHOST"), port=os.getenv("PGPORT"), database=os.getenv("PGDATABASE")) self.curs = self.conn.cursor() self.fetch_tokens() self.scope = [AuthScope.CLIPS_EDIT] self.update_twitch_tokens() self.twitch.set_user_authentication(self.access_token, self.scope, self.refresh_token)
COLOUR_GREEN = 2 COLOUR_YELLOW = 3 COLOUR_BLUE = 4 COLOUR_MAGENTA = 5 COLOUR_CYAN = 6 COLOUR_WHITE = 7 A_BOLD = 1 A_NORMAL = 2 A_REVERSE = 3 A_UNDERLINE = 4 # TWITCH MAX_RESULTS = 10 TWITCH_CLIENT_ID = os.environ.get('TWITCH_CLIENT_ID') TWITCH_CLIENT_SECRET = os.environ.get('TWITCH_CLIENT_SECRET') twitch = Twitch(TWITCH_CLIENT_ID, TWITCH_CLIENT_SECRET) twitch.authenticate_app([]) # RANK # POWERED_BY_ADA = "(c) leocelis.com" POWERED_BY_ADA = "" TOP_GAMES_TITLE = u'{} TOP {} GAMES LIVE' TOP_STREAMS_TITLE = u'{} TOP {} STREAMERS LIVE' TOP_STREAMER_RECORD = "STREAMER CONCURRENT-VIEWERS HIGH-SCORE: {} ({:,})" TOP_GAME_RECORD = "GAME TOP 1 MOST-TIMES HIGH-SCORE: {}" X_POS = 20 def decide_emoji(pos): e = "" if pos == 1:
items = {} for followee in user_followees['data']: items['SOURCE'] = int(user_id) items['TARGET'] = int(followee['to_id']) items['TYPE'] = 'Directed' items['DATE'] = followee['followed_at'] self.store_db(items) if edgePage_cursor and 'cursor' in \ twitch.get_users_follows(after=edgePage_cursor[0], first=100, from_id=user_id)['pagination']: self.followee_parse(user_id, edgePage_cursor) iMaxStackSize = 10000 sys.setrecursionlimit(iMaxStackSize) twitch = Twitch('x5chjai5leju0kgmqu4fh8l6hc5ycu', 'csopzwzqls7ogl2e35jvjm089gbyth') twitch.authenticate_app([]) database = 'The Legend of Zelda.db' conn = sqlite3.connect(database) curr = conn.cursor() n_select = 212 curr.execute( 'SELECT * FROM user_db ORDER BY FOLLOWERS ASC LIMIT {}'.format(n_select)) data = curr.fetchall() Pineline = EdgesPipeline() rank = n_select #descending order, Note: it should be total num. of the database!!! for row in tqdm(data): id = str(row[0])
# from rauth import OAuth2Service from twitchAPI.twitch import Twitch from twitchAPI.types import AuthScope from twitchAPI.oauth import UserAuthenticator scope = [AuthScope.CHANNEL_READ_SUBSCRIPTIONS, AuthScope.BITS_READ] twitch = Twitch("321bx055r6dukooktl98z4bjcc3lxx", "ahuuleft1n1v6lei5onny04vb0kgtn") # twitch.authenticate_app(scope) auth = UserAuthenticator(twitch, scope) token, refresh_token = auth.authenticate() twitch.set_user_authentication(token, scope)
import os import re from pymongo import MongoClient from rich.console import Console from datetime import datetime, timedelta from twitchAPI.twitch import Twitch, VideoType from dotenv import load_dotenv from channel import Channel, Stream load_dotenv("local.env") twitch_key = os.getenv("TWITCH_CLIENT_KEY") twitch_id = os.getenv("TWITCH_CLIENT_ID") or "" twitch_client = Twitch(twitch_id, twitch_key) def get_channels_from_environment() -> list[str]: ch_env: str = os.getenv("DEFAULT_TRACKER_CHANNEL_SOURCE") or "" return ch_env.split(", ") def get_channels_from_database() -> list[str]: mongo_connection_str = os.getenv("MONGO_CONNECTION_STRING") or "" mongo_client: MongoClient = MongoClient(mongo_connection_str) db_name = os.getenv("MONGO_DATABASE_NAME") # TODO rename collection to plural version mdb_channel = mongo_client.get_database(db_name).get_collection("channel") query_results = mdb_channel.find({}, {"channel_name": 1})
print ("other redemption:", title) # Press the green triangle button on the top right of the VSCode window to run the script. if __name__ == '__main__': print('~starting script~') # Create an instance of the REST client. aio = Client(private_const.ADAFRUIT_IO_USERNAME, private_const.ADAFRUIT_IO_KEY) feed = Feed(name="ledfeed") # create instance of twitch API twitch = Twitch(private_const.app_id, private_const.app_secret) twitch.authenticate_app([]) # get ID of user user_info = twitch.get_users(logins=[private_const.username]) user_id = user_info['data'][0]['id'] # set up channel point redemption pubsub target_scope = [AuthScope.CHANNEL_READ_REDEMPTIONS] auth = UserAuthenticator(twitch, target_scope, force_verify=False) token, refresh_token = auth.authenticate() twitch.set_user_authentication(token, target_scope, refresh_token) pubsub = PubSub(twitch) pubsub.start() # you can either start listening before or after you started pubsub.
from twitchAPI.twitch import Twitch import time # create instance of twitch API twitch = Twitch('osqz177phafxe4xiqb2nb34b66lsin', 'vo5id8xvhmyajwpb296s3jqgi1bb0s') twitch.authenticate_app([]) def find_streamer_views(cname): time.sleep(0.1) d = twitch.search_channels(cname) for i in d['data']: if i['display_name'].lower() == cname.lower(): a = twitch.get_streams(user_id=i['id']) break else: return 'n' try: if a['data']: return a['data'][0]['viewer_count'] else: return 'n' except UnboundLocalError: return 'n'
def __init__(self, client_id: str, client_secret: str): self.twitch = Twitch(client_id, client_secret)
from twitchAPI.pubsub import PubSub from uuid import UUID from pprint import pprint import json with open('TwitchSettings.json', 'r') as f: twitchSettings = json.load(f) # Need to read and update channel redemptions scopes = [ AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.CHANNEL_MANAGE_REDEMPTIONS ] twitch = Twitch(twitchSettings["TwitchAppId"], app_secret=None, authenticate_app=False, target_app_auth_scope=scopes) auth = UserAuthenticator(twitch, scopes, force_verify=False) # this will open your default browser and prompt you with the twitch verification website token, refresh_token = auth.authenticate() # add User authentication twitch.set_user_authentication(token, scopes, refresh_token) user_id = twitch.get_users() def channel_points(uuid: UUID, data: dict) -> None: print('got callback for UUID ' + str(uuid)) pprint(data)
def main(followers_prev, twitch): followers = get_follow_count(twitch) if followers != followers_prev: followers_prev = followers title = get_stream_title(twitch) update_stream_title(twitch, title, followers) followers_string = f"Followers: {followers}" with open("followers.txt", "w") as followers_file: followers_file.write(str(followers_string)) return followers_prev if __name__ == "__main__": with open("secrets.json") as secrets_file: secrets = json.load(secrets_file) twitch = Twitch(secrets[0], secrets[1]) target_scope = [AuthScope.CHANNEL_MANAGE_BROADCAST] auth = UserAuthenticator(twitch, target_scope, force_verify=False) token, refresh_token = auth.authenticate() twitch.set_user_authentication(token, target_scope, refresh_token) # followers_prev = get_follow_count(twitch) followers_prev = 0 while True: try: followers_prev = main(followers_prev, twitch) sleep(10) except Exception as e: print(e) sleep(10)
pass items = {} for follower in user_followers['data']: try: items['SOURCE'] = int(follower['from_id']) items['TARGET'] = int(user_id) items['TYPE'] = 'Directed' items['DATE'] = follower['followed_at'] self.store_db(items) except: pass time.sleep(1) twitch = Twitch(twitch_crawler_settings.edges_crawler_id, twitch_crawler_settings.edges_crawler_secrete) twitch.authenticate_app([]) game = twitch_crawler_settings.game database = '{}.db'.format(game) # start the EdgesPipeline Pineline = EdgesPipeline(game) data = Pineline.get_broadcasters() # for each broadcaster, crawl all her followers # then: fetch 100 followers per loop, total loops = follower // 100 for index, row in tqdm(data.iterrows()): id = str(row['Id']) follower = row['FOLLOWERS'] loops = round(follower / 100) + 1
# twitch.py import os import time from dotenv import load_dotenv from twitchAPI.twitch import Twitch import requests load_dotenv() client_id = os.getenv("CLIENT_ID") client_secret = os.getenv("CLIENT_SECRET") twitch = Twitch(client_id, client_secret) twitch.authenticate_app([]) TWITCH_STREAM_API_ENDPOINT_V5 = "https://api.twitch.tv/kraken/streams/{}" API_HEADERS = { 'Client-ID': client_id, 'Accept': 'application/vnd.twitchtv.v5+json', } def is_live(user): # returns true of online userid = twitch.get_users(logins=[user])['data'][0]['id'] url = TWITCH_STREAM_API_ENDPOINT_V5.format(userid) try: req = requests.Session().get(url, headers=API_HEADERS) jsondata = req.json()
class twitch_follower(scrapy.Spider): name = 'followers' start_urls = ['http://quotes.toscrape.com'] items = FollowersItem() twitch = Twitch('x5chjai5leju0kgmqu4fh8l6hc5ycu', 'csopzwzqls7ogl2e35jvjm089gbyth') twitch.authenticate_app([]) pagination_cursor = [] edgePage_cursor = [] i = 1 def parse(self, response): game = twitch_follower.twitch.get_games( names='The Legend of Zelda: Breath of the Wild') gaming_id = game['data'][0]['id'] # page range # for i in range(500): if not twitch_follower.pagination_cursor: # video = twitch_follower.twitch.get_videos(game_id=gaming_id, sort=SortMethod.VIEWS) streams = twitch_follower.twitch.get_streams(first=100, game_id=gaming_id) twitch_follower.pagination_cursor.append( streams['pagination']['cursor']) else: # go to next page streams = twitch_follower.twitch.get_streams( after=twitch_follower.pagination_cursor.pop(), first=100, game_id=gaming_id) twitch_follower.pagination_cursor.append( streams['pagination']['cursor']) print(twitch_follower.i) twitch_follower.i += 1 list_streams = streams['data'] UniqueList_streams = list( {myObject['user_id']: myObject for myObject in list_streams}.values()) for user in UniqueList_streams: user_id = user['user_id'] user_follows = twitch_follower.twitch.get_users_follows( to_id=user_id) user_infos = twitch_follower.twitch.get_users(user_ids=user_id) if user_infos['data']: user_followers = user_follows['total'] view_count = user_infos['data'][0]['view_count'] twitch_follower.items['ID'] = int(user_id) twitch_follower.items['USER'] = int(user_id) twitch_follower.items['FOLLOWERS'] = int(user_followers) twitch_follower.items['view_count'] = int(view_count) yield twitch_follower.items if 'cursor' in twitch_follower.twitch.get_streams( after=twitch_follower.pagination_cursor[0], first=100, game_id=gaming_id)['pagination']: yield scrapy.Request('http://quotes.toscrape.com', callback=self.parse)
from twitchAPI.twitch import Twitch import pandas as pd import sched, time import json from datetime import datetime import psycopg2 ##twitch api input variables client_ID = '' secret = '' #create instance of twitch API twitch = Twitch(client_ID, secret) twitch.authenticate_app([]) ##sql connection = psycopg2.connect(user="", password="", host="localhost", port="", database="twitch_project") ##check if it's midnight def checkIfMidnight(): now = datetime.now() seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() return seconds_since_midnight == 0 #setup dataframe game_data_df = pd.DataFrame(columns = ['',''])
class twitch_follower(scrapy.Spider): name = 'followers' start_urls = ['http://twitch.tv'] items = FollowersItem() game = twitch_crawler_settings.game twitch = Twitch(twitch_crawler_settings.broadcasters_crawler_id, twitch_crawler_settings.broadcasters_crawler_secrete) twitch_v5 = TwitchClient( twitch_crawler_settings.broadcasters_crawler_id, twitch_crawler_settings.broadcasters_crawler_secrete) twitch.authenticate_app([]) pagination_cursor = [] edgePage_cursor = [] i = 1 def parse(self, response): twitch_follower.items['GAME'] = twitch_follower.game game = twitch_follower.twitch.get_games(names=twitch_follower.game) gaming_id = game['data'][0]['id'] # page range if not twitch_follower.pagination_cursor: streams = twitch_follower.twitch.get_streams(first=100, game_id=gaming_id, language='en') twitch_follower.pagination_cursor.append( streams['pagination']['cursor']) else: # go to next page streams = twitch_follower.twitch.get_streams( after=twitch_follower.pagination_cursor.pop(), first=100, game_id=gaming_id, language='en') twitch_follower.pagination_cursor.append( streams['pagination']['cursor']) print(twitch_follower.i) twitch_follower.i += 1 list_streams = streams['data'] UniqueList_streams = list( {myObject['user_id']: myObject for myObject in list_streams}.values()) for user in UniqueList_streams: user_id = user['user_id'] channel = twitch_follower.twitch_v5.channels.get_by_id( channel_id=user_id) videos = twitch_follower.twitch_v5.channels.get_videos( channel_id=user_id, limit=100) gaming_hour = 0 total_hour = 0 user_followers = channel['followers'] view_count = channel['views'] created_at = channel['created_at'] updated_at = channel['updated_at'] if videos: for video in videos: total_hour += video['length'] if video['game'] == twitch_follower.game: gaming_hour += video['length'] if total_hour != 0: dedication = gaming_hour / total_hour if gaming_hour > 1800: # filter out gaming hour <= 30mins broadcasters twitch_follower.items['ID'] = int(user_id) twitch_follower.items['USER'] = int(user_id) twitch_follower.items['FOLLOWERS'] = int(user_followers) twitch_follower.items['view_count'] = int(view_count) twitch_follower.items['created_at'] = created_at twitch_follower.items['updated_at'] = updated_at twitch_follower.items['gaming_hour'] = round( gaming_hour / 3600, 2) twitch_follower.items['total_hour'] = round( total_hour / 3600, 2) twitch_follower.items['dedication'] = round(dedication, 2) yield twitch_follower.items if 'cursor' in twitch_follower.twitch.get_streams( after=twitch_follower.pagination_cursor[0], first=100, game_id=gaming_id, language='en')['pagination']: yield scrapy.Request('http://twitch.tv', callback=self.parse)
subprocess.check_call( [sys.executable, "-m", "pip", "install", "pip install twitchAPI"]) from twitchAPI.twitch import Twitch with open("credentials.json", "r") as credential_file: credentials = json.load(credential_file) def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] # create instance of twitch API twitch = Twitch(app_id=credentials["client id"], app_secret=credentials["app secret"]) twitch.authenticate_app([]) with open("inputlist_user_ids.txt", "r") as ids: user_id_lines = ids.readlines() with open("inputlist_names.txt", "r") as names: name_lines = names.readlines() name_set = set() for name_line in name_lines: name = name_line.strip().lower() name_set.add(name) name_list = list(sorted(name_set)) user_id_set = set()
if __name__ == "__main__": testModule = Twitch_Credential_Maker() scriptArgs = sys.argv skipQuestion = False if len(scriptArgs) != 0: for arg_ in scriptArgs: if arg_ == "autostart": skipQuestion = True credentials_manager = credentials.Credentials_Module() credentials_manager.load_credentials() testModule.credential = credentials_manager.find_Twitch_Credential( config.credentialsNickname) testModule.twitch = Twitch(testModule.credential.pubsub_client_id, testModule.credential.pubsub_secret) #pprint(testModule.twitch.get_users(logins=['thecuriousnerd'])) token, refreshToken = testModule.get_tokens() if not skipQuestion: print("Update credentials file? (y/n)") response = input() if "y" in response.lower(): testModule.updateCredentialsFile(token, refreshToken) print("Ready to close") input() else: testModule.updateCredentialsFile(token, refreshToken) print("Updated Twitch Credentials")
from twitchAPI.webhook import TwitchWebHook from pprint import pprint def callback_stream_changed(uuid, data): print('Callback Stream changed for UUID ' + str(uuid)) pprint(data) def callback_user_changed(uuid, data): print('Callback User changed for UUID ' + str(uuid)) pprint(data) # basic twitch API authentication, this will yield a app token but not a user token twitch = Twitch('your app id', 'your app secret') twitch.authenticate_app([]) # since we want user information, we require a OAuth token, lets get one # you dont need to generate a fresh user token every time, you can also refresh a old one or get one using a different online service # for refreshing look here: https://github.com/Teekeks/pyTwitchAPI#user-authentication # please note that you have to add http://localhost:17563 as a OAuth redirect URL for your app, see the above link for more information auth = UserAuthenticator(twitch, [AuthScope.USER_READ_EMAIL]) token, refresh_token = auth.authenticate() # this will open a webpage twitch.set_user_authentication( token, [AuthScope.USER_READ_EMAIL], refresh_token ) # setting the user authentication so any api call will also use it # setting up the Webhook itself # Please note that the first parameter is the domain your webhook is reachable from the outside, the last parameter # is the port that the Webhook should use hook = TwitchWebHook("https://my.cool.ip:443", 'your app id', 8080) hook.authenticate(
# basic twitch API authentication, this will yield a app token but not a user token auth_scope = [ AuthScope.BITS_READ, AuthScope.USER_EDIT, AuthScope.WHISPERS_READ, AuthScope.CHANNEL_READ_SUBSCRIPTIONS, AuthScope.CHANNEL_READ_STREAM_KEY, AuthScope.ANALYTICS_READ_EXTENSION, AuthScope.ANALYTICS_READ_GAMES, AuthScope.CHANNEL_EDIT_COMMERCIAL, AuthScope.CHANNEL_READ_HYPE_TRAIN, AuthScope.CHANNEL_MANAGE_BROADCAST, AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.CLIPS_EDIT, AuthScope.USER_EDIT_BROADCAST, AuthScope.USER_READ_BROADCAST, AuthScope.USER_READ_EMAIL, AuthScope.USER_EDIT_FOLLOWS, AuthScope.CHANNEL_MODERATE, AuthScope.CHAT_EDIT, AuthScope.CHAT_READ, AuthScope.WHISPERS_READ, AuthScope.WHISPERS_EDIT, AuthScope.MODERATION_READ, AuthScope.CHANNEL_SUBSCRIPTIONS ] twitch = Twitch(APP_ID, APP_SECRET) twitch.authenticate_app(auth_scope) # since we want user information, we require a OAuth token, lets get one # you dont need to generate a fresh user token every time, you can also refresh a old one or get one using a different online service # for refreshing look here: https://github.com/Teekeks/pyTwitchAPI#user-authentication # please note that you have to add http://localhost:17563 as a OAuth redirect URL for your app, see the above link for more information # auth = UserAuthenticator( # twitch, auth_scope) # token, refresh_token = auth.authenticate() # this will open a webpage # print(token, refresh_token) # setting the user authentication so any api call will also use it twitch.set_user_authentication(TOKEN, auth_scope, REFRESH_TOKEN) # setting up the Webhook itself sslContext = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS) hook = TwitchWebHook(PUBLIC_ADDR, APP_ID, PORT, ssl_context=sslContext) # this will use the highest authentication set, which is the user authentication.
telegram_chat_id = os.environ['telegramchatid'] state = 0 streamers = [ 'bananaslamjamma', 'gunnardota2', 'monkeys_forever', 'xcaliburye', 'gorgc', 'purgegamers' ] streamerstate = {} for user_ids in streamers: streamerstate[user_ids] = 0 check_game = operations.check_game bot = operations.send_telegram_photo twitch = Twitch(ClientID, ClientSecret) while True: twitch.authenticate_app([]) for streamername in streamers: data = twitch.get_streams(user_login=[streamername]) if data['data']: streamer = data['data'][0]['user_name'] game_id = data['data'][0]['game_id'] game_name = data['data'][0]['game_name'] stream_title = data['data'][0]['title'] viewers = data['data'][0]['viewer_count'] check_game(game_id, game_name) stream_start_time = datetime.datetime.strptime( data['data'][0]['started_at'], '%Y-%m-%dT%H:%M:%SZ')
return super().default(datetime_object) parser = argparse.ArgumentParser() parser.add_argument('--appid', required=True) parser.add_argument('--appsecret', required=True) parser.add_argument('--html', action='store_true') parser.add_argument('--api', action='store_true') parser.add_argument('--feed', action='store_true') parser.add_argument('--reddit', action='store_true') args = parser.parse_args() if args.appid is not None and args.appsecret is not None: twitch = Twitch(app_id=args.appid, app_secret=args.appsecret) twitch.authenticate_app([]) streams = twitch.get_streams(game_id='30921') reward_streams = [] reward_streams_count = 0 for stream in streams['data']: if 'c2542d6d-cd10-4532-919b-3d19f30a768b' in stream['tag_ids']: user_login = stream['user_login'] user_name = stream['user_name'] title = stream['title'].strip() thumbnail_url = stream['thumbnail_url'].format(width=1280, height=720) started_at = datetime.datetime.strptime(stream['started_at'], '%Y-%m-%dT%H:%M:%SZ') id = stream['id']