1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
|
Chat - Introduction to Middleware
=================================
In this tutorial, we will go over a few examples on how to use and write your own chat command middleware.
Basics
******
Command Middleware can be understood as a set of filters which decide if a chat command should be executed by a user.
A basic example would be the idea to limit the use of certain commands to just a few chat rooms or restricting the use of administrative commands to just the streamer.
There are two types of command middleware:
1. global command middleware: this will be used to check any command that might be run
2. single command middleware: this will only be used to check a single command if it might be run
Example setup
*************
The following basic chat example will be used in this entire tutorial
.. code-block:: python
:linenos:
import asyncio
from twitchAPI import Twitch
from twitchAPI.chat import Chat, ChatCommand
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.types import AuthScope
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
SCOPES = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
TARGET_CHANNEL = ['your_first_channel', 'your_second_channel']
async def command_one(cmd: ChatCommand):
await cmd.reply('This is the first command!')
async def command_two(cmd: ChatCommand):
await cmd.reply('This is the second command!')
async def run():
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, SCOPES)
await helper.bind()
chat = await Chat(twitch, initial_channel=TARGET_CHANNEL)
chat.register_command('one', command_one)
chat.register_command('two', command_two)
chat.start()
try:
input('press Enter to shut down...\n')
except KeyboardInterrupt:
pass
finally:
chat.stop()
await twitch.close()
asyncio.run(run())
Global Middleware
*****************
Given the above example, we now want to restrict the use of all commands in a way that only user :code:`user1` can use them and that they can only be used in :code:`your_first_channel`.
The highlighted lines in the code below show how easy it is to set this up:
.. code-block:: python
:linenos:
:emphasize-lines: 4,28,29
import asyncio
from twitchAPI import Twitch
from twitchAPI.chat import Chat, ChatCommand
from twitchAPI.chat.middleware import UserRestriction, ChannelRestriction
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.types import AuthScope
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
SCOPES = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
TARGET_CHANNEL = ['your_first_channel', 'your_second_channel']
async def command_one(cmd: ChatCommand):
await cmd.reply('This is the first command!')
async def command_two(cmd: ChatCommand):
await cmd.reply('This is the second command!')
async def run():
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, SCOPES)
await helper.bind()
chat = await Chat(twitch, initial_channel=TARGET_CHANNEL)
chat.register_command_middleware(UserRestriction(allowed_users=['user1']))
chat.register_command_middleware(ChannelRestriction(allowed_channel=['your_first_channel']))
chat.register_command('one', command_one)
chat.register_command('two', command_two)
chat.start()
try:
input('press Enter to shut down...\n')
except KeyboardInterrupt:
pass
finally:
chat.stop()
await twitch.close()
asyncio.run(run())
Single Command Middleware
*************************
Given the above example, we now want to only restrict :code:`!one` to be used by the streamer of the channel its executed in.
The highlighted lines in the code below show how easy it is to set this up:
.. code-block:: python
:linenos:
:emphasize-lines: 4, 29
import asyncio
from twitchAPI import Twitch
from twitchAPI.chat import Chat, ChatCommand
from twitchAPI.chat.middleware import StreamerOnly
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.types import AuthScope
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
SCOPES = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
TARGET_CHANNEL = ['your_first_channel', 'your_second_channel']
async def command_one(cmd: ChatCommand):
await cmd.reply('This is the first command!')
async def command_two(cmd: ChatCommand):
await cmd.reply('This is the second command!')
async def run():
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, SCOPES)
await helper.bind()
chat = await Chat(twitch, initial_channel=TARGET_CHANNEL)
chat.register_command('one', command_one, command_middleware=[StreamerOnly()])
chat.register_command('two', command_two)
chat.start()
try:
input('press Enter to shut down...\n')
except KeyboardInterrupt:
pass
finally:
chat.stop()
await twitch.close()
asyncio.run(run())
Using Execute Blocked Handlers
******************************
Execute blocked handlers are a function which will be called whenever the execution of a command was blocked.
You can define a default handler to be used for any middleware that blocks a command execution and/or set one per
middleware that will only be used when that specific middleware blocked the execution of a command.
Note: You can mix and match a default handler with middleware specific handlers as much as you want.
Using a default handler
-----------------------
A default handler will be called whenever the execution of a command is blocked by a middleware which has no specific handler set.
You can define a simple handler which just replies to the user as follows using the global middleware example:
:const:`handle_command_blocked()` will be called if the execution of either :code:`!one` or :code:`!two` is blocked, regardless by which of the two middlewares.
.. code-block:: python
:linenos:
:emphasize-lines: 23, 24, 37
import asyncio
from twitchAPI import Twitch
from twitchAPI.chat import Chat, ChatCommand
from twitchAPI.chat.middleware import UserRestriction, ChannelRestriction
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.types import AuthScope
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
SCOPES = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
TARGET_CHANNEL = ['your_first_channel', 'your_second_channel']
async def command_one(cmd: ChatCommand):
await cmd.reply('This is the first command!')
async def command_two(cmd: ChatCommand):
await cmd.reply('This is the second command!')
async def handle_command_blocked(cmd: ChatCommand):
await cmd.reply(f'You are not allowed to use {cmd.name}!')
async def run():
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, SCOPES)
await helper.bind()
chat = await Chat(twitch, initial_channel=TARGET_CHANNEL)
chat.register_command_middleware(UserRestriction(allowed_users=['user1']))
chat.register_command_middleware(ChannelRestriction(allowed_channel=['your_first_channel']))
chat.register_command('one', command_one)
chat.register_command('two', command_two)
chat.default_command_execution_blocked_handler = handle_command_blocked
chat.start()
try:
input('press Enter to shut down...\n')
except KeyboardInterrupt:
pass
finally:
chat.stop()
await twitch.close()
asyncio.run(run())
Using a middleware specific handler
-----------------------------------
A middleware specific handler can be used to change the response based on which middleware blocked the execution of a command.
Note that this can again be both set for command specific middleware as well as global middleware.
For this example we will only look at global middleware but the method is exactly the same for command specific one.
To set a middleware specific handler, you have to set :const:`~twitchAPI.chat.middleware.BaseCommandMiddleware.execute_blocked_handler`.
For the preimplemented middleware in this library, you can always pass this in the init of the middleware.
In the following example we will be responding different based on which middleware blocked the command.
.. code-block:: python
:linenos:
:emphasize-lines: 23, 24, 27, 28, 36, 37, 38, 39
import asyncio
from twitchAPI import Twitch
from twitchAPI.chat import Chat, ChatCommand
from twitchAPI.chat.middleware import UserRestriction, ChannelRestriction
from twitchAPI.oauth import UserAuthenticationStorageHelper
from twitchAPI.types import AuthScope
APP_ID = 'your_app_id'
APP_SECRET = 'your_app_secret'
SCOPES = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
TARGET_CHANNEL = ['your_first_channel', 'your_second_channel']
async def command_one(cmd: ChatCommand):
await cmd.reply('This is the first command!')
async def command_two(cmd: ChatCommand):
await cmd.reply('This is the second command!')
async def handle_blocked_user(cmd: ChatCommand):
await cmd.reply(f'Only user1 is allowed to use {cmd.name}!')
async def handle_blocked_channel(cmd: ChatCommand):
await cmd.reply(f'{cmd.name} can only be used in channel your_first_channel!')
async def run():
twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, SCOPES)
await helper.bind()
chat = await Chat(twitch, initial_channel=TARGET_CHANNEL)
chat.register_command_middleware(UserRestriction(allowed_users=['user1'],
execute_blocked_handler=handle_blocked_user))
chat.register_command_middleware(ChannelRestriction(allowed_channel=['your_first_channel'],
execute_blocked_handler=handle_blocked_channel))
chat.register_command('one', command_one)
chat.register_command('two', command_two)
chat.start()
try:
input('press Enter to shut down...\n')
except KeyboardInterrupt:
pass
finally:
chat.stop()
await twitch.close()
asyncio.run(run())
Write your own Middleware
*************************
You can also write your own middleware to implement custom logic, you only have to extend the class :const:`~twitchAPI.chat.middleware.BaseCommandMiddleware`.
In the following example, we will create a middleware which allows the command to execute in 50% of the times its executed.
.. code-block:: python
from typing import Callable, Optional, Awaitable
class MyOwnCoinFlipMiddleware(BaseCommandMiddleware):
# it is best practice to add this part of the init function to be compatible with the default middlewares
# but you can also leave this out should you know you dont need it
def __init__(self, execute_blocked_handler: Optional[Callable[[ChatCommand], Awaitable[None]]] = None):
self.execute_blocked_handler = execute_blocked_handler
async def can_execute(cmd: ChatCommand) -> bool:
# add your own logic here, return True if the command should execute and False otherwise
return random.choice([True, False])
async def was_executed(cmd: ChatCommand):
# this will be called whenever a command this Middleware is attached to was executed, use this to update your internal state
# since this is a basic example, we do nothing here
pass
Now use this middleware as any other:
.. code-block:: python
chat.register_command('ban-me', execute_ban_me, command_middleware=[MyOwnCoinFlipMiddleware()])
|