I know that the code is a bit of a mess "frankencode." I've been researching for a while how to get an announce-bot to work and tried many way that don't seem to work anymore. This code works perfectly if one person is streaming, and when that stream ends the announcement is deleted.
The main issue is with the message history check to prevent spam. Originally if anyone messaged, the bot would re-announce after a new message was sent to the channel. I made it so the bot only looks at it's own message history but that means once a second stream was announced it would re-announce the first stream then repeat.
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.get_channel(CHANNELID)
# Defines a loop that will run every 15 seconds
@tasks.loop(seconds=15)
async def live_notifs_loop():
HEADERS = { 'client-id' : 'kimne78kx3ncx6brgo4mv6wki5h1ko' }
GQL_QUERY = """
query($login: String) {
user(login: $login) {
stream {
id
}
}
}
"""
def isLive(username):
QUERY = {
'query': GQL_QUERY,
'variables': {
'login': username
}
}
response = requests.post('https://gql.twitch.tv/gql',
json=QUERY, headers=HEADERS)
dict_response = response.json()
return True if dict_response['data']['user']['stream'] is not None else False
if __name__ == '__main__':
USERS = ['TWITCHNAME1', 'TWITCHNAME2', 'TWITCHNAME3']
for user in USERS:
IS_LIVE = isLive(user)
#print(f'User {user} live: {IS_LIVE}')
if IS_LIVE is True:
# Checks to see if the live message has already been sent.
async for message in channel.history(limit=100):
if message.author == client.user:
# If it has, break the loop (do nothing).
if str('user') in message.content and str("is now streaming") in message.content:
break
else:
await channel.send(
f":red_circle: **LIVE**\n{user} is now streaming on Twitch!"
f"\nhttps://www.twitch.tv/{user}")
print(f"{user} started streaming. Sending a notification.")
break
break
# If they aren't live do this:
else:
async for message in channel.history(limit=100):
# If it was, delete it.
if str('user') in message.content and str("is now streaming") in message.content:
await message.delete()
break
live_notifs_loop.start()
print("Stream Review Stage Complete")