I was testing the correctly function of checking if a user is subscribed to a determinated channel, but it keeps continuosly giving false the is_subscribed function, but i cannot find why, this is my code (i’m using the User token Access):
main.py:
import webbrowser
from configuration_file_telegram import *
from twitch_verification import *
# Credentials
redirect_uri = 'http://localhost/redirect/'
# Genereting auth url
scope = 'user:read:subscriptions' # requested scope
auth_url = f'https://id.twitch.tv/oauth2/authorize?client_id={CLIENT_ID}&redirect_uri={redirect_uri}&response_type=token&scope={scope}'
# opening browser
webbrowser.open(auth_url)
user_id = 'xxx'
channel_id = 'yyy'
# Checking if subscribed
if is_subscribed(user_id, channel_id):
print(f'L\'utente {user_id} è abbonato al canale {channel_id} su Twitch!')
else:
print(f'L\'utente {user_id} non è abbonato al canale {channel_id} su Twitch.')
twitch_verification.py:
import requests
import mysql.connector
from configuration_file_telegram import *
def is_subscribed(user_id, channel_id):
# Connect to DB
db = mysql.connector.connect(
host=SERVER_HOST,
user=SERVER_USERNAME,
password=SERVER_PASSWORD,
database=SERVER_DB
)
# Recovering token
cursor = db.cursor()
cursor.execute("SELECT token FROM tokens ORDER BY id DESC LIMIT 1")
result = cursor.fetchone()
if result:
oauth_token = result[0]
headers = {
'Authorization': f'Bearer {oauth_token}',
'Client-ID': '{CLIENT_ID}'
}
url = f'https://api.twitch.tv/helix/subscriptions/user?broadcaster_id={channel_id}&user_id={user_id}'
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json().get('data')
if data and len(data) > 0:
db.close()
return True
db.close()
return False
index.php (page of redirect after authorization by user):
<script>
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
var url = 'http://localhost/redirect/salva-token.php?'+hash;
window.location.replace(url);
// hash found
} else {
// No hash found
}
</script>
salva-token.php (save-token):
<?php
# Connection to DB
try{
$pdo = new PDO('mysql:host=127.0.0.1; dbname=bot_telegram', 'root', '');
}catch(PDOException $e){
echo 'At line '.e->getLine().' Connection failed: '.$e->getMessage();
exit();
}
# Insert into DB
$accessToken = $_GET['access_token'];
$command = $pdo->prepare("INSERT INTO tokens (token) VALUES (?)");
$command->bindValue(1, $accessToken);
$command->execute();
?>