Bot to ban 404 error return

Hello, I’m trying to set up a bot that will ban problem users on its own (bot, hateful raid, troll, inappropriate nickname, inappropriate behavior, etc.) from a list that I made myself little by little on the different channels where I am a moderator.
concretely I have a “banlist” folder with the users to ban and I update it regularly, I launch the bot about once a week and it must ban these users on all the channels where I am a moderator.

Unfortunately I still end up with a 404 error and impossible to know why, I did check that the users had not been banned from Twitch.
The channels on which I moderate are spelled correctly, a priori there is no problem with the token.

How can I verify that my token has permissions to ban?

If anyone has an idea, I’m a taker.

I must specify that I do not have great skills in development, I use ChatGPT to help me and a computer engineer friend, (but I would like to avoid soliciting him, he is not my employee)

I put the code I use here:

import requests
import time

# Votre clé d'authentification (client ID) Twitch
CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxx'
# Votre clé secrète d'authentification (client secret) Twitch
CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxx'

# Liste des scopes que vous souhaitez demander
SCOPES = ['chat:read', 'chat:edit', 'channel:moderate']

# Liste des chaînes Twitch sur lesquelles vous souhaitez bannir les utilisateurs
chaînes = ['xxxxxxxxxxxxxxxxx']
# Chemin vers le fichier texte contenant la liste des utilisateurs à bannir
fichier_utilisateurs = r'C:\Users\fost6\Documents\Banbot\BanBot 2.0\banlist.txt'
# Raison de bannissement
raison_bannissement = "BanBot"

def lire_utilisateurs(fichier):
    with open(fichier, 'r') as f:
        utilisateurs = f.read().splitlines()
    return utilisateurs

def obtenir_token():
    # URL pour obtenir le token d'accès
    url_token = 'https://id.twitch.tv/oauth2/token'
    params = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'grant_type': 'client_credentials',
        'scope': ' '.join(SCOPES)  # Demander les scopes spécifiés séparés par des espaces
    }
    response = requests.post(url_token, params=params)

    if response.status_code == 200:
        data = response.json()
        access_token = data.get('access_token')
        if access_token:
            print("Token d'accès obtenu avec succès:")
            print(access_token)  # Afficher le token d'accès
            return access_token
        else:
            print("Erreur lors de l'obtention du token d'accès. Aucun token trouvé.")
            return None
    else:
        print(f"Échec de la récupération du token d'accès. Code d'état : {response.status_code}")
        return None

def bannir_utilisateur(nom_utilisateur, chaîne, token, raison):
    # URL de l'endpoint pour bannir un utilisateur sur une chaîne
    url_bannissement = f'https://api.twitch.tv/helix/moderation/banned?broadcaster_id={chaîne}'
    
    headers = {
        'Authorization': f'Bearer {token}',
        'Client-ID': CLIENT_ID
    }

    payload = {
        'user_id': nom_utilisateur,
        'reason': raison
    }

    response = requests.post(url_bannissement, headers=headers, json=payload)

    if response.status_code == 204:
        return 200  # Succès : utilisateur banni avec succès
    else:
        print(f"Échec du bannissement de {nom_utilisateur}. Code d'état : {response.status_code}")
        print(response.json())  # Afficher la réponse JSON en cas d'échec pour déboguer
        return response.status_code  # Retourner le code d'état en cas d'échec

if __name__ == "__main__":
    utilisateurs_a_bannir = lire_utilisateurs(fichier_utilisateurs)
    token = obtenir_token()

    if token:
        print("Début du processus de bannissement...")
        for chaîne in chaînes:
            print(f"Bannir les utilisateurs sur la chaîne {chaîne}:")
            for utilisateur in utilisateurs_a_bannir:
                status_code = bannir_utilisateur(utilisateur, chaîne, token, raison_bannissement)
                if status_code == 200:
                    print(f"{utilisateur} a été banni avec succès.")
                else:
                    print(f"Échec du bannissement de {utilisateur}. Code d'état : {status_code}")
                
                # Attendre une seconde entre chaque requête pour respecter la limite de 30 requêtes par minute
                time.sleep(1)

        print("Fin du processus de bannissement.")

Cordially
eiwinnd

ChatGPT told you to create the wrong kind of token.

To ban people requires a user token

See:

And the ban use documentation

Which API call is 404’ing?

Good morning,

Thanks for your answer, but clearly the documentation is really not clear.

Banning users gives me a 404 error.

Cordially

So what does your code look like now?

Your URL here is wrong

It’s HTTP POST https://api.twitch.tv/helix/moderation/bans

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