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 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 __init__(self, channel: dict[str, str], client: Twitch) -> None: """Initialize the sensor.""" self._client = client self._enable_user_auth = client.has_required_auth( AuthType.USER, OAUTH_SCOPES) self._attr_name = channel["display_name"] self._attr_unique_id = channel["id"]
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 __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 __init__(self, disclient, twitch_id, twitch_sec): self.disclient = disclient self.disclient.loop.create_task(self.get_online_streams()) self.twitch = Twitchy( twitch_id, twitch_sec, ) self.twitch.authenticate_app([]) self.time_format = '%Y-%m-%d %H:%M:%S'
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)
def __init__(self, channel, client: Twitch): """Initialize the sensor.""" self._client = client self._channel = channel self._enable_user_auth = client.has_required_auth(AuthType.USER, OAUTH_SCOPES) self._state = None self._preview = None self._game = None self._title = None self._subscription = None self._follow = None self._statistics = None
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 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 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) client = Twitch(app_id=client_id, app_secret=client_secret) client.auto_refresh_auth = False try: client.authenticate_app(scope=OAUTH_SCOPES) 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=channel, client=client) for channel in channels["data"]], True, )
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.
class TwitchNotifier(commands.Cog): def __init__(self, bot): self.bot: 'PixlBot' = bot self.config = bot.config['TwitchNotifier'] self.backend = FileBackend('db') self.backend.autocommit = True self.bot.logger.info("Twitch notifier plugin ready") self.uuids = [] self.online_uuids = [] self.sslcontext = ssl.SSLContext() self.sslcontext.load_cert_chain(self.config['cert_path'], self.config['key_path']) self._twitch_init_() 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 _login_to_id(self, name: str) -> Optional[str]: """Returns the twitch ID for a given login name, or None if the name couldn't be resolved.""" try: res: dict = self.twitch.get_users(logins=[name]) except TwitchBackendException as e: self.bot.logger.error(f"Backend error fetching user! {e}") return None if len(res) == 0: return None else: return res['data'][0]['id'] def _register_all(self): """Attempts to register stream_changed callbacks for all configured users.""" self.bot.logger.info("Registering callbacks for all watched users..") users = self.backend.filter(TwitchWatchedUser, {'twitch_name': { "$exists": True }}) if not users: self.bot.logger.info("No users to watch. No callbacks registered.") else: for u in users: self.bot.logger.info(f"Registering: {u['twitch_name']}") success, uuid = self.hook.subscribe_stream_changed( u['twitch_id'], self._cb_stream_changed) if success and uuid: self.uuids.append(uuid) self.bot.logger.info( f"{success}: registered subscription UUID: {uuid}") else: self.bot.logger.error( f"{success}: failed registering subscription: {uuid}") def _cb_stream_changed(self, uuid, data): """Callback for Twitch webhooks, fires on stream change event""" self.bot.logger.debug(f"Callback data for {uuid}: {data}") if data["type"] == "offline": if uuid in self.online_uuids: self.online_uuids.remove( uuid ) # Stupid twitch sending the same damn webhook multiple times... return else: self.bot.logger.debug( f"Ignoring duplicate offline callback for {uuid}") return elif data["type"] == "live": if uuid in self.online_uuids: self.bot.logger.debug( f"Ignoring duplicate live callback for {uuid}") return else: self.online_uuids.append(uuid) else: self.bot.logger.error( f"Got a callback type we can't handle: {data['type']}") return if uuid not in self.uuids: self.bot.logger.error( f"Got a callback for a UUID we're not tracking: {uuid}, my UUIDs: {self.uuids}" ) return try: item = self.backend.get(TwitchWatchedUser, {"twitch_id": data["user_id"]}) except TwitchWatchedUser.DoesNotExist: self.bot.logger.error( f"Got a callback for a USER we're not tracking: {data['user_id']} -> {data['user_name']}" ) return channel: discord.TextChannel = self.bot.get_channel( item['notify_channel']) width = 640 height = 360 url = data['thumbnail_url'].format(width=width, height=height) tu = self.twitch.get_users(data['user_id'])['data'][0] self.bot.logger.debug(tu) embed = discord.Embed( title=f"Now streaming {data['game_name']}", description=data['title'], color=discord.Color.green(), ) embed.set_image(url=url) embed.set_thumbnail(url=tu["profile_image_url"]) embed.set_author(name=item["twitch_name"], url=f"https://twitch.tv/{data['user_name']}") embed.add_field(name="Watch live at", value=f"https://twitch.tv/{data['user_name']}") self.bot.loop.create_task( channel. send( # This isn't an async function, so enqueue it manually embed=embed)) self.bot.logger.info( f"Successfully sent online notification for {data['user_id']}") @cog_ext.cog_subcommand( base="Twitchwatch", name="add_notification", description="Add a go live notification for Twitch", options=[twitch_name, notify_channel, notify_text], guild_ids=util.guilds) async def add_notification(self, ctx: SlashContext, twitch_name: str, notify_channel: discord.TextChannel, notify_text: str): twitch_id = self._login_to_id(twitch_name) try: self.backend.get(TwitchWatchedUser, {'twitch_name': twitch_name}) except TwitchWatchedUser.DoesNotExist: pass except TwitchWatchedUser.MultipleDocumentsReturned: self.bot.logger.error( "Multiple users returned - database inconsistent???") return if not twitch_id: await ctx.send(embed=mkembed( 'error', f"Unable to get the Twitch ID for the name {twitch_name}")) return await ctx.defer() # This bit can take a minute. success, uuid = self.hook.subscribe_stream_changed( twitch_id, self._cb_stream_changed) if success and uuid: self.uuids.append(uuid) self.bot.logger.info( f"{success}: registered subscription UUID: {uuid}") else: self.bot.logger.error( f"{success}: failed registering subscription: {uuid}") await ctx.send("Bluh, couldn't register the webhook with twitch :(" ) return item = TwitchWatchedUser({ 'twitch_name': twitch_name, 'twitch_id': twitch_id, 'discord_name': ctx.author.id, 'notify_channel': notify_channel.id, 'notify_text': notify_text, 'uuid': str(uuid) }) self.bot.logger.debug(f"DB object dump: {item.__dict__}") self.backend.save(item) await ctx.send(embed=mkembed("done", f"Notification added for {twitch_name}", channel=notify_channel.name)) @cog_ext.cog_subcommand( base="Twitchwatch", name="del_notification", description="Remove a go live notification for Twitch", options=[twitch_name], guild_ids=util.guilds) async def del_notification(self, ctx: SlashContext, twitch_name: str): try: item = self.backend.get(TwitchWatchedUser, {'twitch_name': twitch_name}) except TwitchWatchedUser.DoesNotExist: await ctx.send(embed=mkembed( "error", f"No notification exists for {twitch_name}")) return self.hook.unsubscribe(item['uuid']) self.bot.logger.info(f"Removing watch {item['uuid']}: {twitch_name}") self.backend.delete(item) if item['uuid'] in self.uuids: self.uuids.remove(item['uuid']) await ctx.send( embed=mkembed("done", f"Notification for {twitch_name} removed."))
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)
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")
class TwitchState(): """API documentation https://dev.twitch.tv/docs/api/reference#get-streams """ 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 streamer_factory(self, usr, discord_name, data): """Creates a streamer object to be stored.""" stream_bro = self.twitch.get_users(logins=[usr]) if len(stream_bro) > 0: self.cfg.setProperty("Streamers", data, discord_name) return stream_bro else: return False def get_live_channel_id(self): return self.LIVE_CHANNEL_ID def get_client_id(self): return self.CLIENT_ID def get_client_secret(self): return self.CLIENT_SECRET def get_oauth_token(self): return self.OAUTH_TOKEN def get_headers(self): return self.HEADERS def is_user_live(self, username, returnData=False): endpoint = 'https://api.twitch.tv/helix/streams' #endpoint = 'http://localhost:17563' my_params = {'user_login': username} response = requests.get(endpoint, headers=self.get_headers(), params=my_params) data = response.json()['data'] #pprint(data) if len(data) == 0: return False if returnData: return data return data[0]['type'] == 'live'
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()
# 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.
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(
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)
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')
class DiscordTwitchWebhook(): 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 authenticate(self): self.authenticated = False try: self.twitch.authenticate_app([]) self.hook.authenticate(self.twitch) except TwitchAuthorizationException: print("Twitch authentication failed") except RuntimeError: print("Webhook must be https") else: self.authenticated = True return self.authenticated def subscribe_user(self, user: DiscordTwitchCallback): if not self.authenticated: raise Exception #TODO handle more exceptions user_data = self.twitch.get_users(logins=[user.username]) user.data = user_data['data'][0] user.id = user.data['id'] if user not in self.subscriptions: ret, user.uuid = self.hook.subscribe_stream_changed( user.id, self.callback_stream_changed) if ret: self.subscriptions.append(user) else: print(f"Failed to subscribe to {user.username}") def unsubscribe_user(self, user: DiscordTwitchCallback): #TODO return def start(self): self.hook.start() def stop(self): self.hook.unsubscribe_all(self.twitch) self.hook.stop() def callback_stream_changed(self, uuid, twdata): print('Callback for UUID ' + str(uuid), twdata) user = next((user for user in self.subscriptions if user.uuid == uuid), None) if user == None: print("Callback failed") return if twdata['type'] == 'live': emb = self.create_embed(twdata) user.run_callback(emb) def create_embed(self, twdata): return Embed(title=f"{twdata['user_name']}", description=f"{twdata['user_name']} is streaming {twdata['game_name']}! Get in here!", color=6570404, url=f"https://twitch.tv/{twdata['user_name']}") \ .set_image(url=twdata['thumbnail_url'].format(width="1280", height="720"))