{"id":15519820,"url":"https://github.com/tomaarsen/twitchwebsocket","last_synced_at":"2025-04-23T04:41:30.957Z","repository":{"id":62585767,"uuid":"173570494","full_name":"tomaarsen/TwitchWebsocket","owner":"tomaarsen","description":"Python Wrapper for easily connecting to Twitch and setting up a chat bot.","archived":false,"fork":false,"pushed_at":"2021-10-26T18:54:21.000Z","size":90,"stargazers_count":9,"open_issues_count":2,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-19T20:48:39.623Z","etag":null,"topics":["bot","python","twitch","twitch-bot","twitchbot"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tomaarsen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-03T12:15:24.000Z","updated_at":"2024-12-16T18:42:07.000Z","dependencies_parsed_at":"2022-11-03T22:05:48.802Z","dependency_job_id":null,"html_url":"https://github.com/tomaarsen/TwitchWebsocket","commit_stats":null,"previous_names":["cubiedev/twitchwebsocket"],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tomaarsen%2FTwitchWebsocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tomaarsen%2FTwitchWebsocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tomaarsen%2FTwitchWebsocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tomaarsen%2FTwitchWebsocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tomaarsen","download_url":"https://codeload.github.com/tomaarsen/TwitchWebsocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241979201,"owners_count":20052092,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bot","python","twitch","twitch-bot","twitchbot"],"created_at":"2024-10-02T10:22:57.913Z","updated_at":"2025-03-05T06:30:34.973Z","avatar_url":"https://github.com/tomaarsen.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TwitchWebsocket\nPython Wrapper for easily connecting to Twitch and setting up a chat bot.\n\n---\n\n# Input\nThis module will require the following information to be passed:\n\n| **Type**       | **Explanation** | **Example**                            | **Variable Name** | **Required?** |\n| -------------- | ---------------- | ---------------------- | ----------------- | ------------- |\n| Host           | The socket host | \"irc.chat.twitch.tv\"                   | host | Y |\n| Port           | The socket port | 6667                                   | port | Y |\n| Channel        | The channel to connect to | \"#CubieDev\"                            | chan | Y |\n| Nickname       | The name of the bot | \"CubieB0T\"                             | nick | Y |\n| Authentication | The authentication of the bot | \"oauth:pivogip8ybletucqdz4pkhag6itbax\" | auth | Y |\n| Callback       | The function that gets called with all messages | Any function which receives one param  | callback | Y |\n| Capability | List of extra information to be requested from Twitch. (See Twitch docs) | [\"membership\", \"tags\", \"commands\"] | capability | N |\n| Live | Whether the outputs should actually be sent or only printed in the console | True | live | N |\n\n*Note that the example OAuth token is not an actual token, but merely a generated string to give an indication what it might look like.*\n\nI got my real OAuth token from https://twitchapps.com/tmi/.\n\n---\n\n# Output\nThe callback function will be given back a Message object. This object has no methods and is merely parsed storage of the information given by Twitch. It has the following variables (assuming m is a Message object):\n\n**Variable**    | **Type**  | **Example Data** |\n--------------- | --------- | ---------------- |\n m.full_message | str       | @badges=broadcaster/1;color=#00FF7F;display-name=CubieDev;emotes=;flags=;id=3d623460-0bcb-4e65-9167-4b8d435e768d;mod=0;room-id=94714716;subscriber=0;tmi-sent-ts=1551617354820;turbo=0;user-id=94714716;user-type= :cubiedev!cubiedev@cubiedev.tmi.twitch.tv PRIVMSG #cubiedev :This is a test message for clarification purposes |\n m.tags         | dict      | {'badges': 'broadcaster/1', 'color': '#00FF7F', 'display-name': 'CubieDev', 'emotes': '', 'flags': '', 'id': '3d623460-0bcb-4e65-9167-4b8d435e768d', 'mod': '0', 'room-id': '94714716', 'subscriber': '0', 'tmi-sent-ts': '1551617354820', 'turbo': '0', 'user-id': '94714716', 'user-type': ''} |\n m.command      | str       | cubiedev!cubiedev@cubiedev.tmi.twitch.tv PRIVMSG #cubiedev |\n m.user         | str       | cubiedev |\n m.type         | str       | PRIVMSG |\n m.params       | str       | #cubiedev |\n m.channel      | str       | cubiedev |\n m.message      | str       | This is a test message for clarification purposes |\n\nWhat these variables hold is shown here:\n\n    # How messages are parsed, and what the Message class attributes represent:\n    # @badges=subscriber/0;color=#00FF7F;display-name=CubieDev;emotes=;flags=;id=d315b88f-7813-467a-a1fc-418b00d4d5ee;mod=0;room-id=70624819;subscriber=1;tmi-sent-ts=1550060037421;turbo=0;user-id=94714716;user-type= :cubiedev!cubiedev@cubiedev.tmi.twitch.tv PRIVMSG #flackblag :Hello World!\n    # |                                                                                                                                                                                                               |  |      |                                 |     | |        |  |          |\n    # +---------------------------------------------------------------------------------------------------[ TAGS ]----------------------------------------------------------------------------------------------------+  [ USER ]                                 [TYPE ] [ PARAMS ]  [ MESSAGE  ]\n\n    # |                                                                                                                                                                                                                 |                                                          |             |\n    # |                                                                                                                                                                                                                 +-----------------------[ COMMAND ]------------------------+             |\n    # |                                                                                                                                                                                                                                                                                          |\n    # +-------------------------------------------------------------------------------------------------------------------------------------[ FULL_MESSAGE ]-------------------------------------------------------------------------------------------------------------------------------------+\n\nPrinting out the Message object also gives some information on what everything means:\n```\nfull_message: @badges=broadcaster/1;color=#00FF7F;display-name=CubieDev;emotes=;flags=;id=3d623460-0bcb-4e65-9167-4b8d435e768d;mod=0;room-id=94714716;subscriber=0;tmi-sent-ts=1551617354820;turbo=0;user-id=94714716;user-type= :cubiedev!cubiedev@cubiedev.tmi.twitch.tv PRIVMSG #cubiedev :This is a test message for clarification purposes\n        tags: {'badges': 'broadcaster/1', 'color': '#00FF7F', 'display-name': 'CubieDev', 'emotes': '', 'flags': '', 'id': '3d623460-0bcb-4e65-9167-4b8d435e768d', 'mod': '0', 'room-id': '94714716', 'subscriber': '0', 'tmi-sent-ts': '1551617354820', 'turbo': '0', 'user-id': '94714716', 'user-type': ''}\n        command: cubiedev!cubiedev@cubiedev.tmi.twitch.tv PRIVMSG #cubiedev\n                user: cubiedev\n                type: PRIVMSG\n                params: #cubiedev\n        message: This is a test message for clarification purposes\n```\n\n---\n\n# Usage:\n```python\nclass MyBot:\n    def __init__(self):\n        self.host = \"irc.chat.twitch.tv\"\n        self.port = 6667\n        self.chan = \"#\u003cchannel_name\u003e\"\n        self.nick = \"\u003cuser_name\u003e\"\n        self.auth = \"oauth:\u003cauthentication\u003e\"\n        \n        # Send along all required information, and the bot will start \n        # sending messages to your callback function. (self.message_handler in this case)\n        self.ws = TwitchWebsocket(host=self.host, \n                                  port=self.port,\n                                  chan=self.chan,\n                                  nick=self.nick,\n                                  auth=self.auth,\n                                  callback=self.message_handler,\n                                  capability=[\"membership\", \"tags\", \"commands\"],\n                                  live=True)\n        self.ws.start_blocking()\n        # Any code after this will be executed after a KeyboardInterrupt\n\n    def message_handler(self, m):\n        # Create your bot functionality here.\n        pass\n\nif __name__ == \"__main__\":\n    MyBot()\n```\n| **Method with Parameters** | **Meaning** |\n| -------------------------- | ----------- |\n| ws = TwitchWebsocket(str host, str port, function message_handler, bool live) | message_handler is a function or method which will receive a Message object. If live is true, then any messages sent with ws.send_message() will appear in chat, otherwise they will just be printed out in the console. |\n| ws.login(str nick, str auth) | Logs in to Twitch using the username and authentication |\n| ws.join_channel(str channel) | Joins the channel |\n| ws.add_capability(str capability) | Adds a single [capability](https://dev.twitch.tv/docs/irc/membership/). |\n| ws.add_capability(list capabilities) | Adds all [capabilities](https://dev.twitch.tv/docs/irc/membership/) in the list. |\n| ws.leave() | Leave a channel |\n| ws.send_pong() | Send Pong. This is already done automatically upon receiving a Ping. |\n| ws.send_ping() | Send a Ping. Can be useful for testing connectivity. |\n| ws.send_message(str message) | Send message to Twitch Chat. | \n| ws.send_whisper(str sender, str message) | Whisper sender with message |\n\n---\n# My personal Twitch Bot Template\n```python\nfrom TwitchWebsocket import TwitchWebsocket\nimport json\n\nclass Settings:\n    def __init__(self, bot):\n        try:\n            # Try to load the file using json.\n            # And pass the data to the MyBot class instance if this succeeds.\n            with open(\"settings.txt\", \"r\") as f:\n                settings = f.read()\n                data = json.loads(settings)\n                bot.set_settings(data['Host'],\n                                data['Port'],\n                                data['Channel'],\n                                data['Nickname'],\n                                data['Authentication'])\n        except ValueError:\n            raise ValueError(\"Error in settings file.\")\n        except FileNotFoundError:\n            # If the file is missing, create a standardised settings.txt file\n            # With all parameters required.\n            with open('settings.txt', 'w') as f:\n                standard_dict = {\n                                    \"Host\": \"irc.chat.twitch.tv\",\n                                    \"Port\": 6667,\n                                    \"Channel\": \"#\u003cchannel\u003e\",\n                                    \"Nickname\": \"\u003cname\u003e\",\n                                    \"Authentication\": \"oauth:\u003cauth\u003e\"\n                                }\n                f.write(json.dumps(standard_dict, indent=4, separators=(',', ': ')))\n                raise ValueError(\"Please fix your settings.txt file that was just generated.\")\n\nclass MyBot:\n    def __init__(self):\n        self.host = None\n        self.port = None\n        self.chan = None\n        self.nick = None\n        self.auth = None\n        \n        # Fill previously initialised variables with data from the settings.txt file\n        Settings(self)\n\n        self.ws = TwitchWebsocket(host=self.host, \n                                  port=self.port,\n                                  chan=self.chan,\n                                  nick=self.nick,\n                                  auth=self.auth,\n                                  callback=self.message_handler,\n                                  capability=[\"membership\", \"tags\", \"commands\"],\n                                  live=False)\n        self.ws.start_blocking()\n\n    def set_settings(self, host, port, chan, nick, auth):\n        self.host = host\n        self.port = port\n        self.chan = chan\n        self.nick = nick\n        self.auth = auth\n\n    def message_handler(self, m):\n        if m.type == \"PRIVMSG\":\n            pass\n\nif __name__ == \"__main__\":\n    MyBot()\n```\n---\n\n# Example\n\nHere's a list of some personal projects of mine implementing this library.\n* [TwitchMarkovChain](https://github.com/CubieDev/TwitchMarkovChain)\n* [TwitchAIDungeon](https://github.com/CubieDev/TwitchAIDungeon)\n* [TwitchGoogleTranslate](https://github.com/CubieDev/TwitchGoogleTranslate)\n* [TwitchCubieBotGUI](https://github.com/CubieDev/TwitchCubieBotGUI)\n* [TwitchCubieBot](https://github.com/CubieDev/TwitchCubieBot)\n* [TwitchRandomRecipe](https://github.com/CubieDev/TwitchRandomRecipe)\n* [TwitchUrbanDictionary](https://github.com/CubieDev/TwitchUrbanDictionary)\n* [TwitchRhymeBot](https://github.com/CubieDev/TwitchRhymeBot)\n* [TwitchWeather](https://github.com/CubieDev/TwitchWeather)\n* [TwitchDeathCounter](https://github.com/CubieDev/TwitchDeathCounter)\n* [TwitchSuggestDinner](https://github.com/CubieDev/TwitchSuggestDinner)\n* [TwitchPickUser](https://github.com/CubieDev/TwitchPickUser)\n* [TwitchSaveMessages](https://github.com/CubieDev/TwitchSaveMessages)\n* [TwitchMMLevelPickerGUI](https://github.com/CubieDev/TwitchMMLevelPickerGUI) (Mario Maker 2 specific bot)\n* [TwitchMMLevelQueueGUI](https://github.com/CubieDev/TwitchMMLevelQueueGUI) (Mario Maker 2 specific bot)\n* [TwitchPackCounter](https://github.com/CubieDev/TwitchPackCounter) (Streamer specific bot)\n* [TwitchDialCheck](https://github.com/CubieDev/TwitchDialCheck) (Streamer specific bot)\n* [TwitchSendMessage](https://github.com/CubieDev/TwitchSendMessage) (Meant for debugging purposes)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomaarsen%2Ftwitchwebsocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftomaarsen%2Ftwitchwebsocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomaarsen%2Ftwitchwebsocket/lists"}