项目作者: Teekeks

项目描述 :
A Python 3.7 implementation of the Twitch API and its Webhook
高级语言: Python
项目地址: git://github.com/Teekeks/pyTwitchAPI.git
创建时间: 2020-03-23T19:30:51Z
项目社区:https://github.com/Teekeks/pyTwitchAPI

开源协议:MIT License

下载


Python Twitch API

PyPI version Downloads Python version Twitch API version Documentation Status

This is a full implementation of the Twitch Helix API, PubSub, EventSub and Chat in python 3.7+.

Installation

Install using pip:

pip install twitchAPI

Documentation and Support

A full API documentation can be found on readthedocs.org.

For support please join the Twitch API discord server

Usage

Basic API calls

Setting up an Instance of the Twitch API and get your User ID:

  1. from twitchAPI.twitch import Twitch
  2. from twitchAPI.helper import first
  3. import asyncio
  4. async def twitch_example():
  5. # initialize the twitch instance, this will by default also create a app authentication for you
  6. twitch = await Twitch('app_id', 'app_secret')
  7. # call the API for the data of your twitch user
  8. # this returns a async generator that can be used to iterate over all results
  9. # but we are just interested in the first result
  10. # using the first helper makes this easy.
  11. user = await first(twitch.get_users(logins='your_twitch_user'))
  12. # print the ID of your user or do whatever else you want with it
  13. print(user.id)
  14. # run this example
  15. asyncio.run(twitch_example())

Authentication

The Twitch API knows 2 different authentications. App and User Authentication.
Which one you need (or if one at all) depends on what calls you want to use.

It’s always good to get at least App authentication even for calls where you don’t need it since the rate limits are way better for authenticated calls.

Please read the docs for more details and examples on how to set and use Authentication!

App Authentication

App authentication is super simple, just do the following:

  1. from twitchAPI.twitch import Twitch
  2. twitch = await Twitch('my_app_id', 'my_app_secret')

User Authentication

To get a user auth token, the user has to explicitly click “Authorize” on the twitch website. You can use various online services to generate a token or use my build in Authenticator.
For my Authenticator you have to add the following URL as a “OAuth Redirect URL”: http://localhost:17563
You can set that here in your twitch dev dashboard.

  1. from twitchAPI.twitch import Twitch
  2. from twitchAPI.oauth import UserAuthenticator
  3. from twitchAPI.type import AuthScope
  4. twitch = await Twitch('my_app_id', 'my_app_secret')
  5. target_scope = [AuthScope.BITS_READ]
  6. auth = UserAuthenticator(twitch, target_scope, force_verify=False)
  7. # this will open your default browser and prompt you with the twitch verification website
  8. token, refresh_token = await auth.authenticate()
  9. # add User authentication
  10. await twitch.set_user_authentication(token, target_scope, refresh_token)

You can reuse this token and use the refresh_token to renew it:

  1. from twitchAPI.oauth import refresh_access_token
  2. new_token, new_refresh_token = await refresh_access_token('refresh_token', 'client_id', 'client_secret')

AuthToken refresh callback

Optionally you can set a callback for both user access token refresh and app access token refresh.

  1. from twitchAPI.twitch import Twitch
  2. async def user_refresh(token: str, refresh_token: str):
  3. print(f'my new user token is: {token}')
  4. async def app_refresh(token: str):
  5. print(f'my new app token is: {token}')
  6. twitch = await Twitch('my_app_id', 'my_app_secret')
  7. twitch.app_auth_refresh_callback = app_refresh
  8. twitch.user_auth_refresh_callback = user_refresh

EventSub

EventSub lets you listen for events that happen on Twitch.

The EventSub client runs in its own thread, calling the given callback function whenever an event happens.

There are multiple EventSub transports available, used for different use cases.

See here for more info about EventSub in general and the different Transports, including code examples: on readthedocs

PubSub

PubSub enables you to subscribe to a topic, for updates (e.g., when a user cheers in a channel).

A more detailed documentation can be found here on readthedocs

  1. from twitchAPI.pubsub import PubSub
  2. from twitchAPI.twitch import Twitch
  3. from twitchAPI.helper import first
  4. from twitchAPI.type import AuthScope
  5. from twitchAPI.oauth import UserAuthenticator
  6. import asyncio
  7. from pprint import pprint
  8. from uuid import UUID
  9. APP_ID = 'my_app_id'
  10. APP_SECRET = 'my_app_secret'
  11. USER_SCOPE = [AuthScope.WHISPERS_READ]
  12. TARGET_CHANNEL = 'teekeks42'
  13. async def callback_whisper(uuid: UUID, data: dict) -> None:
  14. print('got callback for UUID ' + str(uuid))
  15. pprint(data)
  16. async def run_example():
  17. # setting up Authentication and getting your user id
  18. twitch = await Twitch(APP_ID, APP_SECRET)
  19. auth = UserAuthenticator(twitch, [AuthScope.WHISPERS_READ], force_verify=False)
  20. token, refresh_token = await auth.authenticate()
  21. # you can get your user auth token and user auth refresh token following the example in twitchAPI.oauth
  22. await twitch.set_user_authentication(token, [AuthScope.WHISPERS_READ], refresh_token)
  23. user = await first(twitch.get_users(logins=[TARGET_CHANNEL]))
  24. # starting up PubSub
  25. pubsub = PubSub(twitch)
  26. pubsub.start()
  27. # you can either start listening before or after you started pubsub.
  28. uuid = await pubsub.listen_whispers(user.id, callback_whisper)
  29. input('press ENTER to close...')
  30. # you do not need to unlisten to topics before stopping but you can listen and unlisten at any moment you want
  31. await pubsub.unlisten(uuid)
  32. pubsub.stop()
  33. await twitch.close()
  34. asyncio.run(run_example())

Chat

A simple twitch chat bot.
Chat bots can join channels, listen to chat and reply to messages, commands, subscriptions and many more.

A more detailed documentation can be found here on readthedocs

Example code for a simple bot

  1. from twitchAPI.twitch import Twitch
  2. from twitchAPI.oauth import UserAuthenticator
  3. from twitchAPI.type import AuthScope, ChatEvent
  4. from twitchAPI.chat import Chat, EventData, ChatMessage, ChatSub, ChatCommand
  5. import asyncio
  6. APP_ID = 'my_app_id'
  7. APP_SECRET = 'my_app_secret'
  8. USER_SCOPE = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
  9. TARGET_CHANNEL = 'teekeks42'
  10. # this will be called when the event READY is triggered, which will be on bot start
  11. async def on_ready(ready_event: EventData):
  12. print('Bot is ready for work, joining channels')
  13. # join our target channel, if you want to join multiple, either call join for each individually
  14. # or even better pass a list of channels as the argument
  15. await ready_event.chat.join_room(TARGET_CHANNEL)
  16. # you can do other bot initialization things in here
  17. # this will be called whenever a message in a channel was send by either the bot OR another user
  18. async def on_message(msg: ChatMessage):
  19. print(f'in {msg.room.name}, {msg.user.name} said: {msg.text}')
  20. # this will be called whenever someone subscribes to a channel
  21. async def on_sub(sub: ChatSub):
  22. print(f'New subscription in {sub.room.name}:\\n'
  23. f' Type: {sub.sub_plan}\\n'
  24. f' Message: {sub.sub_message}')
  25. # this will be called whenever the !reply command is issued
  26. async def test_command(cmd: ChatCommand):
  27. if len(cmd.parameter) == 0:
  28. await cmd.reply('you did not tell me what to reply with')
  29. else:
  30. await cmd.reply(f'{cmd.user.name}: {cmd.parameter}')
  31. # this is where we set up the bot
  32. async def run():
  33. # set up twitch api instance and add user authentication with some scopes
  34. twitch = await Twitch(APP_ID, APP_SECRET)
  35. auth = UserAuthenticator(twitch, USER_SCOPE)
  36. token, refresh_token = await auth.authenticate()
  37. await twitch.set_user_authentication(token, USER_SCOPE, refresh_token)
  38. # create chat instance
  39. chat = await Chat(twitch)
  40. # register the handlers for the events you want
  41. # listen to when the bot is done starting up and ready to join channels
  42. chat.register_event(ChatEvent.READY, on_ready)
  43. # listen to chat messages
  44. chat.register_event(ChatEvent.MESSAGE, on_message)
  45. # listen to channel subscriptions
  46. chat.register_event(ChatEvent.SUB, on_sub)
  47. # there are more events, you can view them all in this documentation
  48. # you can directly register commands and their handlers, this will register the !reply command
  49. chat.register_command('reply', test_command)
  50. # we are done with our setup, lets start this bot up!
  51. chat.start()
  52. # lets run till we press enter in the console
  53. try:
  54. input('press ENTER to stop\n')
  55. finally:
  56. # now we can close the chat bot and the twitch api client
  57. chat.stop()
  58. await twitch.close()
  59. # lets run our setup
  60. asyncio.run(run())