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()
# 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 pubsub.unlisten(uuid) pubsub.stop()
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)
def start(self): self.pubsub = PubSub(self.twitch) #self.pubsub.ping_frequency = 30 self.pubsub.start() print("started")
class Twitch_Pubsub(): 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 setup(self): self.twitch.authenticate_app(self.target_scope) self.twitch.set_user_authentication( self.credential.pubsub_AccessToken, self.target_scope, self.credential.pubsub_RefreshToken) def get_tokens(self): self.twitch.authenticate_app(self.target_scope) for scope_ in self.target_scope: print(scope_) auth = UserAuthenticator(self.twitch, self.target_scope, force_verify=config.FORCE_Verify_Credentials) token, refresh_token = auth.authenticate() if token is not None: print("found token") if refresh_token is not None: print("found refresh_token") print(token) print(refresh_token) self.twitch.set_user_authentication(token, self.target_scope, refresh_token) def start(self): self.pubsub = PubSub(self.twitch) #self.pubsub.ping_frequency = 30 self.pubsub.start() print("started") def next(self): user_id = self.twitch.get_users( logins=[config.autoJoin_TwitchChannel])['data'][0]['id'] if user_id is not None: print("found user_id") print(user_id) self.uuid_whisper = self.pubsub.listen_whispers( user_id, self.callback_whisper) self.uuid_channelPoints = self.pubsub.listen_channel_points( user_id, self.callback_channelPoints) self.uuid_bits = self.pubsub.listen_bits(user_id, self.callback_bits) self.uuid_subs = self.pubsub.listen_channel_subscriptions( user_id, self.callback_subs) #input('press ENTER to close...') def stop(self): self.pubsub.unlisten(self.uuid_whisper) self.pubsub.unlisten(self.uuid_channelPoints) self.pubsub.unlisten(self.uuid_bits) self.pubsub.unlisten(self.uuid_subs) self.pubsub.stop() def callback_whisper(self, uuid: UUID, data: dict) -> None: print('got callback for UUID ' + str(uuid)) pprint(data) def callback_channelPoints(self, uuid: UUID, data: dict) -> None: print("Channel Point Redemption") print('got callback for UUID ' + str(uuid)) pprint(data) #print("attempting to get data: ") #print(data['data']['redemption']['user']['display_name']) #print(data['data']['redemption']['reward']['title']) #print(data['data']['redemption']['reward']['prompt']) try: userinput = data['data']['redemption']['user_input'] except: userinput = "" praxis_logger_obj.log("\n\n") praxis_logger_obj.log( data['data']['redemption']['user']['display_name']) praxis_logger_obj.log(data['data']['redemption']['reward']['title']) praxis_logger_obj.log( AbstractChannelRewards.ChannelRewardsType.channelPoints) praxis_logger_obj.log(data['data']['redemption']['reward']['prompt']) praxis_logger_obj.log(userinput) praxis_logger_obj.log(data) self.callback_EXEC( data['data']['redemption']['user']['display_name'], data['data']['redemption']['reward']['title'], AbstractChannelRewards.ChannelRewardsType.channelPoints, data['data']['redemption']['reward']['prompt'], userinput, data) def callback_bits(self, uuid: UUID, data: dict) -> None: print("Bits Redemption") print('got callback for UUID ' + str(uuid)) pprint(data) praxis_logger_obj.log(data['data']['user_name']) try: userinput = data['data']['chat_message'] praxis_logger_obj.log(data['data']['chat_message']) except: userinput = "" praxis_logger_obj.log(data) self.callback_EXEC( data['data']['user_name'], "TwitchBits", AbstractChannelRewards.ChannelRewardsType.twitch_bits, userinput, data['data']['bits_used'], data) def callback_subs(self, uuid: UUID, data: dict) -> None: print("Subs Redemption") print('got callback for UUID ' + str(uuid)) pprint(data) try: userinput = data['message']['sub_message']['message'] except: userinput = "" self.callback_EXEC( data['message']['display_name'], "TwitchSub", AbstractChannelRewards.ChannelRewardsType.twitch_subs, userinput, "", data) def callback_EXEC(self, sender, rewardName: str, rewardType, rewardPrompt, userInput, raw_data): try: is_actionable = self.is_reward(rewardName, rewardType) if is_actionable: praxis_logger_obj.log("Trying to do the thing") #if self.cooldownModule.isCooldownActive("twitchpubsub") == False: self.exec_reward(sender, rewardName, rewardType, rewardPrompt, userInput, raw_data) except: print("something went wrong with a reward") def is_reward(self, rewardName, rewardType): # todo need to url-escape word clean_param = urlencode({ 'reward_name': rewardName, 'reward_type': rewardType }) print(rewardName, rewardType) #standalone_channelrewards url = "http://standalone_channelrewards:42069/api/v1/reward?%s" % clean_param resp = requests.get(url) return resp.status_code == 200 def exec_reward(self, sender, rewardName, rewardType, rewardPrompt, userInput, realMessage): params = urlencode({ 'reward_source': channel_rewards.channelRewards_base.AbstractChannelRewards. ChannelRewardsSource.Twitch, 'user_name': sender, 'reward_name': rewardName, 'reward_type': rewardType, 'reward_prompt': rewardPrompt, 'user_input': userInput, 'bonus_data': realMessage }) #standalone_channelrewards url = "http://standalone_channelrewards:42069/api/v1/exec_reward?%s" % params resp = requests.get(url) if resp.status_code == 200: print("Got the following message: %s" % resp.text) data = loads(resp.text) msg = data['message'] if msg is not None: #self.send_message(msg) #Cant Send messages with this pubsub library afaik pass else: # todo handle failed requests pass #FINISH THIS EVENT LOG def send_EventLog(self, eventName, eventTime, eventType, eventSender, eventData): params = urlencode({ 'event_name': eventName, 'event_time': eventTime, 'event_type': eventType, 'eventSender': eventSender, 'event_data': eventData }) url = "http://standalone_eventlog:42008/api/v1/event_log/add_event?%s" % params resp = requests.get(url) if resp.status_code == 200: print("Got the following message: %s" % resp.text) data = loads(resp.text) msg = data['message'] if msg is not None: return msg # todo send to logger and other relevent services else: # todo handle failed requests pass
twitch.authenticate_app([]) target_scope = [AuthScope.WHISPERS_READ, AuthScope.CHANNEL_READ_REDEMPTIONS, AuthScope.CHANNEL_SUBSCRIPTIONS, AuthScope.BITS_READ] auth = UserAuthenticator(twitch, target_scope, force_verify=False) # this will open your default browser and prompt you with the twitch verification website token, refresh_token = auth.authenticate() print(token, refresh_token) # add User authentication twitch.set_user_authentication(token, target_scope, refresh_token) # starting up PubSub pubsub = PubSub(twitch) pubsub.start() user_id = twitch.get_users(logins=[TWITCH_CHANNEL_NAME])['data'][0]['id'] pprint(twitch.get_users(logins=[TWITCH_CHANNEL_NAME])) # you can either start listening before or after you started pubsub. # uuid1 = pubsub.listen_whispers(user_id, callback_function) uuid2 = pubsub.listen_channel_points(user_id, callback_function) uuid3 = pubsub.listen_channel_subscriptions(user_id, callback_function) uuid4 = pubsub.listen_bits(user_id, callback_function) # print(uuid2) input('press ENTER to close...') # you do not need to unlisten to topics before stopping but you can listen and unlisten at any moment you want
) else: HUE_KEY = resp["success"]["username"] print( f"Your key is: {HUE_KEY}\nEdit the script and add this key to `HUE_KEY` to skip this step in the future." ) # setting up Authentication and getting your user id twitch.authenticate_app([]) target_scope = [AuthScope.CHANNEL_READ_REDEMPTIONS] auth = UserAuthenticator(twitch, target_scope, force_verify=False) # this will open your default browser and prompt you with the twitch verification website token, refresh_token = auth.authenticate() twitch.set_user_authentication(token, target_scope, refresh_token) user_id = twitch.get_users(logins=[USERNAME])['data'][0]['id'] # starting up PubSub pubsub = PubSub(twitch) pubsub.start() # you can either start listening before or after you started pubsub. uuid = pubsub.listen_whispers(user_id, callback) # uuid = pubsub.listen_channel_points(user_id, callback) input('press ENTER to close...\n') # you do not need to unlisten to topics before stopping but you can listen and unlisten at any moment you want pubsub.unlisten(uuid) pubsub.stop()
# 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") print("\n press ENTER to close") rekters.Reset() # Start pubsub pubsub = PubSub(twitch) pubsub.start() # We save the uuid provided to unlisten later uuid = pubsub.listen_channel_points(user_id, Channel_Pt_Controller) input("press ENTER to close") pubsub.unlisten(uuid) pubsub.stop()