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) 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 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( twitch ) # this will use the highest authentication set, which is the user authentication. # some hooks don't require any authentication, which would remove the requirement to set up a https reverse proxy # if you don't require authentication just dont call authenticate() hook.start() # the hook has to run before you subscribe to any events since the twitch api will do a handshake this this webhook as soon as you subscribe success, uuid_stream = hook.subscribe_stream_changed('your user id', callback_stream_changed)
# 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)
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. print('~connected to twitch~') # listen to channel points. enter callback function when redemption occurs uuid = pubsub.listen_channel_points(user_id, callback_channel_points) # two ways to end code: press ENTER or ctrl+c in terminal try: input('listening. press ENTER to close when done streaming...\n') # you do not need to unlisten to topics before stopping but you can listen and unlisten at any moment you want
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) # starting up PubSub pubsub = PubSub(twitch) pubsub.start() # you can either start listening before or after you started pubsub. uuid = pubsub.listen_channel_points(user_id, channel_points)
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. hook.authenticate(twitch) # some hooks don't require any authentication, which would remove the requirement to set up a https reverse proxy # if you don't require authentication just dont call authenticate() hook.start() user_info = twitch.get_users() user_id = user_info['data'][0]['id'] print(f'User ID : {user_id}') # the hook has to run before you subscribe to any events since the twitch api will do a handshake this this webhook as soon as you subscribe success, uuid_stream = hook.subscribe_stream_changed(str(user_id),
class TwitchClip(commands.Cog): 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) @commands.command(aliases=['c']) async def clip(self, ctx, streamer): """Get a Twitch Clip""" self.update_twitch_tokens() # Get the streamer's ID streamer_info = self.streamer_check(streamer) if len(streamer_info) == 0: embed = discord.Embed(title="Streamer not found", color=discord.Colour.from_rgb(255, 0, 0)) await ctx.send(embed=embed) return streamer_id = streamer_info[0]['id'] create_clip = self.twitch.create_clip(broadcaster_id=streamer_id) if 'error' in create_clip: embed = discord.Embed(title=f"{create_clip['message']}", color=discord.Colour.from_rgb(255, 0, 0)) await ctx.send(embed=embed) return elif len(create_clip['data']) == 0: embed = discord.Embed(title="Streamer not found", color=discord.Colour.from_rgb(255, 0, 0)) await ctx.send(embed=embed) return clip_url = f"https://clips.twitch.tv/{create_clip['data'][0]['id']}" await ctx.send(clip_url) def update_twitch_tokens(self): self.fetch_tokens() # refresh twitch new_tokens = refresh_access_token(self.refresh_token, self.client_id, self.client_secret) self.access_token = new_tokens[0] self.refresh_token = new_tokens[1] # Update the access token update_access_query = f"UPDATE twitchclips SET token = '{new_tokens[0]}' WHERE id = 2" update_refresh_query = f"UPDATE twitchclips SET token = '{new_tokens[1]}' WHERE id = 3" self.curs.execute(update_access_query) self.curs.execute(update_refresh_query) def fetch_tokens(self): self.curs.execute("SELECT * FROM twitchclips") rows = self.curs.fetchall() for row in rows: if row[0] == 2: self.access_token = row[2] if row[0] == 3: self.refresh_token = row[2] def streamer_check(self, streamer): if streamer == "tt" or streamer == "t1" or streamer == "t": streamer = "loltyler1" elif streamer == "x" or streamer == "cow": streamer = "xqcow" elif streamer == "dlift" or streamer == "lift": streamer = "doublelift" return self.twitch.get_users(logins=[streamer])['data']
from twitchAPI.pubsub import PubSub from twitchAPI.twitch import Twitch from twitchAPI.types import AuthScope from uuid import UUID from your_stuff import your_id, your_secret, your_oa, your_username import rekters # Authentication Setup and Info twitch = Twitch(your_id, your_secret) twitch.authenticate_app([]) twitch.set_user_authentication(your_oa, [AuthScope.CHANNEL_READ_REDEMPTIONS], your_oa) user_id = twitch.get_users(logins=[your_username])['data'][0]['id'] # Controllers def Channel_Pt_Controller(uuid: UUID, data: dict) -> None: redeemer = data["data"]["redemption"]["user"]["display_name"] reward = data["data"]["redemption"]["reward"]["title"] command = data["data"]["redemption"]["user_input"] command = command.lower() print(redeemer + " Is going to rek you.") if reward == "Do a little dance": rekters.Do_Alittle_Dance(command, 5) print("\n press ENTER to close") elif reward == "Shoot'em Up": rekters.Mouse_Hold(command, 5) print("\n press ENTER to close") else: print("That reward doesn't exist")