IRC with Python - Login fails

Hey together!

I try to get access to the irc for the twitch chat but somehow it does not work I dont understand why.

I requested a user access token with scopes “chat:read” and “chat:edit”.
After that I tried to connect to the twitch irc.
In my mIRC I tried to set the token as “oauth:” as password. Same in HexIRC and also in my own mini python script for my first tests…

I always get the error:

tmi.twitch.tv NOTICE * :Login authentication failed

My username is my twitch username in lowercase.

An example Python code (not great but I thought it should at least work somehow…):

import socket
import re

if __name__ == "__main__":
    HOST = "irc.chat.twitch.tv"
    #HOST = "irc-ws.chat.twitch.tv"

    PORT = 6667
    #PORT = 80
    NICK = "roin93" #The account Name
    PASS = "somekeyfromme"
    CHAN = "#roin93"

    s = socket.socket()
    s.connect((HOST, PORT))
    s.send("PASS oauth:{}\r\n".format(PASS).encode() )
    s.send("NICK {}\r\n".format(NICK).encode())
    s.send("JOIN {}\r\n".format(CHAN).encode())

    while True:
        resp = s.recv(1024)
        print(resp)
        if resp == "PING :tmi.twitch.tv\r\n".encode():
            s.send("PONG :tmi.twitch.tv\r\n".encode())
        if resp.find("hi".encode()) != -1:
            s.send(("PRIVMSG "+CHAN+" :HELLO\r\n").encode())

        resp = ""

The raw IRC from mIRC looks like this:

-> irc.chat.twitch.tv CAP LS 302
-> irc.chat.twitch.tv PASS oauth:somekeyfromme
-> irc.chat.twitch.tv NICK roin93
-> irc.chat.twitch.tv USER roin93 0 * :...
<- :tmi.twitch.tv CAP * LS :twitch.tv/commands twitch.tv/membership twitch.tv/tags
-> irc.chat.twitch.tv CAP LIST
-> irc.chat.twitch.tv CAP END
<- :tmi.twitch.tv NOTICE * :Login authentication failed

Any Idea what I am doing wrong? I just dont get it.

Can you demonstrate what you did you generate the user access token?

If you use your token against the validate endpoint does it return a UserID in the payload.

Example from example tool

Interesting. I requested a fresh user access token and your tool says it is an invalid token.
I generate my user access token by using this script stuff:

from flask import Flask
from flask import request
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

import threading
import time

from config.app_credentials import client_id

def get_user_access_token(scopes=[]):
    app = Flask(__name__)
    io_loop = None
    http_server = None
    scope_string = ' '.join(scopes)

    code = None
    received = False

    @app.route("/")
    def root():
        baseURL = "https://id.twitch.tv/oauth2/authorize"
        redirectUri = "http://localhost:25000/callback"
        url = baseURL + '?response_type=code&client_id=' + client_id + '&redirect_uri=' + redirectUri + '&scope=' + scope_string

        # TODO Create fancy html page with a button to go to the twitch logon page
        return "Landing page on the server.\n <a href='" + url + "'>Authorize user account from Twitch</a>"

    @app.route("/callback")
    def callback():
        nonlocal received
        nonlocal code

        code = request.args.get('code')
        if code is None:
            print("Callback ohne Code Parameter aufgerufen!")
        received = True
        return code

    def start_server():
        nonlocal io_loop
        nonlocal http_server

        # Start its own IOLoop
        io_loop = IOLoop()
        io_loop.make_current()

        # Defining the server
        http_server = HTTPServer(WSGIContainer(app))
        http_server.listen(25000)

        # Start the actual processing of the server
        io_loop.current(instance=False).start()

        print("Server is stopped now.")

    def stop_server():
        nonlocal http_server
        nonlocal io_loop
        http_server.stop()
        io_loop.make_current()
        io_loop.current(instance=False).stop()
        io_loop = None
        http_server = None

    tserver = threading.Thread(target=start_server, daemon=True)
    tserver.start()

    # Wait until the Twitch Auth process called our callback page.
    while not received:
        time.sleep(0.1)
    time.sleep(0.1)

    stop_server()

    return code

I just call the function with a scope array like ["chat:edit", "chat:read"]

It opens a simple webserver with a link on it. I click the link, get redirected to twitch to authorize it and then I have a new key. When I now call the link at the page, I just get redirected to my callback page with a new token - Twitch probably saved that I used this client id and so on for my account with the exact same scopes and does not ask again if it is a valid request, right?

How can it be invalid right when i requested it?

You don’t seem to be exchanging the returned code for an Access Token, which is step 3 in the Auth Code flow https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-authorization-code-flow

Looks like I missed that somehow. I will try that next. Thanks. It works! I just forgot the request of the real access token…

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.