Esempio n. 1
0
TWITCH_CLIENT_ID = os.environ.get('TWITCH_CLIENT_ID')
TWITCH_CLIENT_SECRET = os.environ.get('TWITCH_CLIENT_SECRET')
MAX_PAGES = 5  # times 100

# create instance of twitch API
twitch = Twitch(TWITCH_CLIENT_ID, TWITCH_CLIENT_SECRET)
twitch.authenticate_app([])

# ====================
# get top streamers
# ====================
cursor = 1
page = 1
while cursor:
    if cursor == 1:
        streams = twitch.get_streams(first=100)
    else:
        streams = twitch.get_streams(after=cursor, first=100)

    for stream in streams.get('data', {}):
        print(stream)
        stream_id = stream.get('id')

        if stream_id:
            r = get_top_stream_last_entry(stream_id=stream_id)

            # get the last viewer count
            if r:
                last_viewer_count = r.get('viewer_count', 0)
            else:
                last_viewer_count = stream.get('viewer_count', 0)
Esempio n. 2
0
class Streamer:

    global TWITCH_APP_ID
    global TWITCH_SECRET
    global StreamerName
    global StreamerID
    isID = False

    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 getUserID(self):

        if self.isID: return self.StreamerName

        self.twitch.authenticate_app([])
        data = self.twitch.get_users(logins=[self.StreamerName])
        return data['data'][0]['id']


    def isStreaming(self):

        data = self.twitch.get_streams(user_id=self.StreamerID)
        if len(data['data']) != 0:
            if data['data'][0]['type'] == 'live':
                return True
        return False

    def getStreamLink(self): return 'https://www.twitch.tv/' + str(self.StreamerName.lower())

    def lock(self): self.LOCK = True

    def unlock(self): self.LOCK = False

    def lockStatus(self): return self.LOCK

    def getGame(self):

        if self.isStreaming():
            data = self.twitch.get_streams(user_id=self.StreamerID)
            game = data['data'][0]['game_name']
            return game
        return False

    def getViewers(self):

        if self.isStreaming():
            data = self.twitch.get_streams(user_id=self.StreamerID)
            viewers = data['data'][0]['viewer_count']
            return viewers
        return False

    def getTitle(self):

        if self.isStreaming():
            data = self.twitch.get_streams(user_id=self.StreamerID)
            title = data['data'][0]['title']
            return  title
        return False

    def getThumbnail(self):

        if self.isStreaming():
            data = self.twitch.get_streams(user_id=self.StreamerID)
            thumbnail = data['data'][0]['thumbnail_url']
            thumbnail = thumbnail.format(width='1920', height='1080')
            return thumbnail
        return False

    def getProfilePicture(self):

        data = self.twitch.get_users(logins=self.StreamerName)
        picture = data['data'][0]['profile_image_url']
        return picture

    def getStreamerName(self):
        return self.StreamerName
Esempio n. 3
0
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']

      reward_stream = {'user_login': user_login, 'user_name': user_name, 'title': title, 'thumbnail_url': thumbnail_url, 'started_at': started_at, 'id': id}
Esempio n. 4
0
class TwitchAPIHandler:
    """
    A wrapper to interact with the twitch API
    """
    def __init__(self, client_id: str, client_secret: str):
        self.twitch = Twitch(client_id, client_secret)

    def get_streams_data(self, usernames):
        """
        Gets all stream information from a list of given usernames
        :param usernames: The list of usernames
        :return: The JSON data of the request
        """
        result = []
        batches = split_to_100s(usernames)
        for batch in batches:
            batch_result = []
            try:
                batch_result.extend(
                    self.twitch.get_streams(user_login=batch).get("data"))
            except TwitchAPIException:
                logger.error(
                    f"Streams data not received for batch, invalid request")
                for user in batch:
                    try:
                        batch_result.extend(
                            self.twitch.get_streams(
                                user_login=user).get("data"))
                    except TwitchAPIException:
                        logger.error(
                            "User data cannot be found, invalid request")

            result.extend(batch_result)

        return result

    def get_user_data(self, usernames=None, ids=None):
        """
        Gets the user information of a given user

        :param usernames: The display twitch usernames of the users
        :param ids: The unique twitch ids of the users
        :return: The JSON information of the user's data
        """
        result = []

        if usernames:
            user_list = split_to_100s(usernames)
            for u_batch in user_list:
                result += self.twitch.get_users(logins=u_batch).get("data")

        if ids:
            id_list = split_to_100s(ids)
            for id_batch in id_list:
                result += self.twitch.get_users(logins=id_batch).get("data")

        return result

    def get_game_data(self, game_id):
        """
        Gets the game information of a given game
        :param game_id: The twitch game ID of a game
        :return: The JSON information of the game's data
        """
        if game_id != "":
            game_data = self.twitch.get_games(game_ids=game_id)
            return game_data.get("data")[0]
        else:
            return None

    def get_team_users(self, team_id):
        """
        Gets the users data about a given team
        :param team_id: The team name of the twitch team
        :return: the JSON information of the users
        """
        return (self.get_team_data(team_id)).get("users")

    def get_team_data(self, team_id):
        """
        Gets the users data about a given team
        :param team_id: The team name of the twitch team
        :return: the JSON information of the users
        """
        a = self.twitch.get_teams(name=team_id)
        return a.get("data")[0]
Esempio n. 5
0
class Twitch(commands.Cog):
    """Get live updates for your favourite twitch streamers
    """
    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'

    async def get_online_streams(self):
        await self.disclient.wait_until_ready()
        print('Looking for live Twitch streams!')
        while not self.disclient.is_closed():
            try:
                # print("checking twitch")
                check = get_all_twitch_channels_to_check(3)
                if not check:
                    await asyncio.sleep(60)
                    continue
                if len(check) > 100:
                    # need to split list into lengths of 100 in future
                    # get_streams only takes 100 inputs at a time
                    check = check[:99]
                ids = [str(x) for x in check.keys()]
                b = self.twitch.get_streams(user_id=ids)
                for stream in b["data"]:
                    c = self.twitch.get_users(user_ids=stream["user_id"])
                    linkend = c['data'][0]['login']
                    link = f"https://www.twitch.tv/{linkend}"
                    username = stream['user_name']
                    desc = stream['title']
                    msg = f"`{username}` is live! {link}"
                    image_url = f"""{stream['thumbnail_url'].format(
                                     width=852, height=480)}?{str(datetime.datetime.now().timestamp())}"""
                    embed = discord.Embed(title=msg,
                                          description=desc,
                                          color=discord.Color.purple())
                    embed.set_image(url=image_url)
                    embed.add_field(name='Playing', value=stream['game_name'])
                    check_time = datetime.datetime.strptime(
                        stream['started_at'], '%Y-%m-%dT%H:%M:%SZ')
                    check_time.strftime(self.time_format)
                    if check[int(stream['user_id'])] != check_time:
                        update_twitch_last_live(stream['user_id'], check_time)
                    else:
                        continue
                    channels = get_channels_following_twitch_stream(
                        stream['user_id'])
                    if not channels:
                        await asyncio.sleep(60)
                        continue
                    for chan in channels:
                        channel = self.disclient.get_channel(int(chan))
                        # set ping roles up in the future
                        # gid = channel.guild.id
                        # rol = self.disclient.get_guild(gid).roles
                        # tr = discord.utils.get(rol, name="twitch")
                        await channel.send(
                            embed=embed
                        )  # content=tr.mention, for when roles are assigned
            except Exception as e:
                print(e)
            # delay 60 seconds before checking again
            await asyncio.sleep(60)

    @commands.command(
        aliases=['followstream', 'follow_stream', 'followtwitch'])
    @commands.guild_only()
    @commands.has_permissions(administrator=True)
    async def follow_twitch(self, ctx, stream):
        """Follows a twitch stream in this channel! Live updates will be posted here.
        .follow_twitch <username or link>"""
        channel = ctx.channel.id
        if "twitch.tv" in stream:
            stream = stream.split("/")[-1].lower()
        else:
            stream = stream.lower()
        user = self.twitch.get_users(logins=stream)
        print(user)
        if not user:
            await ctx.send(
                embed=error_embed(f"Failed to find Twitch user {stream}!"))
            return
        for d in user["data"]:
            ayed = str(d["id"])
            add_channel(channel)
            add_twitch_channel_to_db(ayed)
            followed = follow_twitch_channel_db(channel, ayed)
            if followed:
                display_name = d['display_name']
                profile_image = d['profile_image_url']
                link = f"https://www.twitch.tv/{d['login']}"
                msg = f'This channel will now receive updates on when {display_name} goes live at {link}'
                embed = discord.Embed(
                    title=f'Successfully Followed {display_name}!',
                    description=msg,
                    color=discord.Color.purple())
                embed.set_thumbnail(url=profile_image)
                await ctx.send(embed=embed)
            else:
                await ctx.send(embed=error_embed(
                    f"Failed to follow {stream} in this channel!"))

    @commands.command(
        aliases=['unfollowstream', 'unfollow_stream', 'unfollowtwitch'])
    @commands.guild_only()
    @commands.has_permissions(administrator=True)
    async def unfollow_twitch(self, ctx, stream):
        """Unfollows a twitch stream followed in this channel.
        .unfollow_twitch <username or link>"""
        channel = ctx.channel.id
        if "twitch.tv" in stream:
            stream = stream.split("/")[-1].lower()
        else:
            stream = stream.lower()
        user = self.twitch.get_users(logins=stream)
        if not user:
            await ctx.send(
                embed=error_embed(f"Failed to find Twitch user {stream}!"))
            return
        for d in user["data"]:
            ayed = str(d["id"])
            unfollowed = unfollow_twitch_channel_db(channel, ayed)
            if unfollowed:
                await ctx.send(embed=success_embed(
                    f"Unfollowed {stream} in this channel!"))
            else:
                await ctx.send(embed=error_embed(
                    f"Failed to unfollow {stream} in this channel!"))

    @commands.command(name='twitch', aliases=['twitchs', 'twitches'])
    @commands.guild_only()
    async def twitches(self, ctx):
        """Returns a list of all twitch users followed in this server!"""
        guild = ctx.guild
        chans = get_all_twitch_followed_in_guild()
        chan_dict = {}
        for pair in chans:
            if pair[0] not in chan_dict:
                chan_dict.update({pair[0]: [pair[-1]]})
            else:
                chan_dict[pair[0]].append(pair[-1])
        msg = ''
        for channel in guild.channels:
            if channel.id in chan_dict:
                for twitch in chan_dict[channel.id]:
                    twitch_str = str(twitch)
                    twitch = self.twitch.get_users(user_ids=[twitch_str])
                    twitch = twitch['data'][0]['login']
                    spacing = 39 - len(channel.name + twitch)
                    chan_str = f"`#{channel.name}{' ' * spacing}{twitch}`\n"
                    msg = msg + chan_str
        if msg == '':
            await ctx.send(
                embed=error_embed('No Twitch streams followed in this server!')
            )
        else:
            add_to_start = f"`Channel Name{' ' * 17}Twitch User`\n"
            msg = add_to_start + msg
            embed = discord.Embed(
                title=f'Twitch Streams Followed in {guild.name}!',
                description=msg,
                color=discord.Color.purple())
            await ctx.send(embed=embed)