Skip to content

Commit

Permalink
Merge pull request #37 from acuifex/store-refresh-token
Browse files Browse the repository at this point in the history
Store twitch refresh token, ignore some stuff
  • Loading branch information
Pinsplash authored Apr 26, 2023
2 parents 982caf8 + a2d9734 commit 7b139b7
Show file tree
Hide file tree
Showing 3 changed files with 187 additions and 7 deletions.
160 changes: 160 additions & 0 deletions twitch-integration/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
Binary file not shown.
34 changes: 27 additions & 7 deletions twitch-integration/twitch_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
from collections import Counter
from typing import Optional

from twitchAPI.oauth import refresh_access_token
from twitchAPI import Twitch
from twitchAPI.oauth import UserAuthenticator
from twitchAPI.types import AuthScope, ChatEvent
from twitchAPI.types import AuthScope, ChatEvent, TwitchAPIException
from twitchAPI.chat import Chat, EventData, ChatMessage
# noinspection PyUnresolvedReferences
import obspython as obs
from rcon.source import rcon
from rcon.exceptions import WrongPassword
Expand All @@ -14,6 +16,7 @@
APP_ID = ''
APP_SECRET = ''
USER_SCOPE = [AuthScope.CHAT_READ]
REFRESH_TOKEN = ''
TARGET_CHANNEL = ''
SOURCE_NAME = ''
RCON_HOST = "127.0.0.1"
Expand Down Expand Up @@ -107,12 +110,21 @@ async def game_loop():


async def try_starting_twitch():
global chat, twitch
global chat, twitch, REFRESH_TOKEN
if APP_ID != "" and APP_SECRET != "" and twitch is None:
twitch = await Twitch(APP_ID, APP_SECRET)
auth = UserAuthenticator(twitch, USER_SCOPE)
token, refresh_token = await auth.authenticate()
await twitch.set_user_authentication(token, USER_SCOPE, refresh_token)
token = None
if REFRESH_TOKEN != "":
print("refreshing token")
try:
token, REFRESH_TOKEN = await refresh_access_token(REFRESH_TOKEN, APP_ID, APP_SECRET)
except TwitchAPIException as e:
print("token refresh failed", e)
if token is None:
print("querying new token")
auth = UserAuthenticator(twitch, USER_SCOPE)
token, REFRESH_TOKEN = await auth.authenticate()
await twitch.set_user_authentication(token, USER_SCOPE, REFRESH_TOKEN)

chat = await Chat(twitch)
chat.register_event(ChatEvent.READY, on_ready)
Expand All @@ -138,7 +150,9 @@ async def shutdown_twitch():

async def startup():
global poll_task
await asyncio.sleep(1) # since we're running in a thread, we need to wait for obs to set our properties.
# since we're running in a thread, we need to wait for obs to set our properties.
# TODO: change this to a future or some other kind of awaitable?
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
poll_task = loop.create_task(game_loop())
await try_starting_twitch()
Expand Down Expand Up @@ -246,14 +260,20 @@ def script_update(settings):
obs.obs_data_array_release(obs_votes_keywords)
print("data updated")


def script_save(settings):
obs.obs_data_set_string(settings, "refresh_token", REFRESH_TOKEN)

# https://gist.github.com/serializingme/5c1a6fd6c7ea58af77c7b80579737c5a

def script_load(settings):
global _LOOP, _THREAD, REFRESH_TOKEN
REFRESH_TOKEN = obs.obs_data_get_string(settings, "refresh_token")

# let's be nice, and only call the obs's methods from its own thread.
# TODO: call this every frame because why not?
obs.timer_add(update_source, 1000)

global _LOOP, _THREAD
_LOOP = asyncio.new_event_loop()

def async_thread():
Expand Down

0 comments on commit 7b139b7

Please sign in to comment.