Compare commits

..

No commits in common. "61a1d52bf8501416001fabeddd5624a12db5e60b" and "f9a64cfeb504f15c5791a4d586170872a35f7676" have entirely different histories.

3 changed files with 282 additions and 407 deletions

View file

@ -1,6 +1,5 @@
CONSUMER_KEY=
CONSUMER_SECRET=
BEARER_TOKEN=
TOKEN= TOKEN=
TOKEN_SECRET= TOKEN_SECRET=
CONSUMER_KEY=
CONSUMER_SECRET=
PSEUDO= PSEUDO=

View file

@ -2,26 +2,33 @@
Bot qui envoie automatiquement des réponses ennuyantes quand les personnes que tu suis finissent leur tweet par un mot spécial. Bot qui envoie automatiquement des réponses ennuyantes quand les personnes que tu suis finissent leur tweet par un mot spécial.
Certains mots peuvent servir de "trigger" sans être dans la liste, example : `aussi` n'est pas dans la liste, mais en retirant `aus`, on obtient `si`, qui est dans la liste.
| Mot | Réponse | ¦ | Mot | Réponse | ¦ | Mot | Réponse | ¦ | Mot | Réponse | ¦ | Mot | Réponse | ¦ | Mot | Réponse
------|--------- |:-:|---------|-----------|:-:|------|-------------------------------|:-:|-------------------------|------------|:-:|-------|------------------ |:-:|-------|-
quoi | feur | ¦ | con | combre | ¦ | coup | teau | ¦ | ka | pitaine | ¦ | moi | tié/sson/sissure | ¦ | ni | cotine
oui | stiti/fi | ¦ | ok | sur glace | ¦ | ça | pristi/perlipopette/von | ¦ | fais | rtile | ¦ | toi | lette/ture | ¦ | quand | dide/tal/didat
non | bril | ¦ | ouais | stern | ¦ | bon | jour/soir (dépend de l'heure) | ¦ | tant (ou autre syntaxe) | gente | ¦ | top | inambour | ¦ | sol | itaire
nan | cy | ¦ | comment | tateur | ¦ | qui | wi/mono | ¦ | et | eint/ain | ¦ | jour | nal | ¦ | vois | ture
hein | deux | ¦ | mais | on | ¦ | sur | prise | ¦ | la | vabo/vande | ¦ | ya/yo | hourt/yo | ¦ | akhy | nator
ci | tron | ¦ | fort | boyard | ¦ | pas | nini/steur | ¦ | tki | la | ¦ | re | pas/veil/tourne | ¦ |
N'hésitez pas à ouvrir un ticket ou faire une merge-request pour contribuer au projet. N'hésitez pas à ouvrir un ticket ou faire une merge-request pour contribuer au projet.
## Lancer le Bot ## Lancer le Bot
Donner la permission au minimum `Read and Write` au bot dans `Settings` puis `App permissions`. Donner la permission `Read and Write` (ou `Read + Write + Direct Messages` mais aucun DM n'est envoyé) au bot dans `Settings` puis `App permissions`.
Les codes fourni par l'API de Twitter sont généralements disponible dans la page `Keys and tokens`.
Détails des variables d'environnement : Détails des variables d'environnement :
| Variable | Explication et où elle se trouve | Variable | Explication et où elle se trouve
| --------------- |- ----------------|-
| TOKEN | Token d'accès disponible dans la section `Authentication Tokens` sous la sous-rubrique `Access Token and Secret` TOKEN | Token d'accès disponible dans la section `Authentication Tokens` sous la sous-rubrique `Access Token and Secret`
| TOKEN_SECRET | Token d'accès secret disponible dans la section `Authentication Tokens` sous la sous-rubrique `Access Token and Secret` TOKEN_SECRET | Token d'accès secret disponible dans la section `Authentication Tokens` sous la sous-rubrique `Access Token and Secret`
| CONSUMER_KEY | Clé API disponible dans la section `Consumer Keys` sous la sous-rubrique `API Key and Secret` CONSUMER_KEY | Clé API disponible dans la section `Consumer Keys`
| CONSUMER_SECRET | Clé secrète API disponible dans la section `Consumer Keys` sous la sous-rubrique `API Key and Secret` CONSUMER_SECRET | Clé secrète API disponible dans la section `Consumer Keys`
| BEARER_TOKEN | Token disponible dans la section `Authentication Tokens` sous la sous-rubrique `Bearer Token` PSEUDOS | Pseudos du ou des compte.s que vous voulez écouter pour le snipe (a séparer avec une virgule **sans** espaces)
| PSEUDOS | Pseudos du ou des compte.s que vous voulez écouter pour le snipe (a séparer avec une virgule **sans** espaces) WHITELIST | Pseudos des comptes qui ne seront pas touché par le Bot (facultatif, a séparer avec une virgule **sans** espaces, par défaut la liste est vide)
| WHITELIST | Pseudos des comptes qui ne seront pas touché par le Bot (facultatif, a séparer avec une virgule **sans** espaces, par défaut la liste est vide) VERBOSE | Affiche plus de messages dans la console [False\|True] (facultatif, par défaut sur False)
| VERBOSE | Affiche plus de messages dans la console [False\|True] (facultatif, par défaut sur False) FORCELIST | Force le bot à écouter certains comptes (séparer les comptes avec une virgule **sans** espaces, par défaut la liste est vide)
| FORCELIST | Force le bot à écouter certains comptes (séparer les comptes avec une virgule **sans** espaces, par défaut la liste est vide)
### En local ### En local
@ -39,11 +46,10 @@ docker build https://git.kennel.ml/Anri/feurBot.git#main --tag feurbot:main && \
docker run -d \ docker run -d \
--name="feurBot" \ --name="feurBot" \
feurbot:main \ feurbot:main \
--CONSUMER_KEY="" \
--CONSUMER_SECRET="" \
--BEARER_TOKEN="" \
--TOKEN="" \ --TOKEN="" \
--TOKEN_SECRET="" \ --TOKEN_SECRET="" \
--CONSUMER_KEY="" \
--CONSUMER_SECRET="" \
--PSEUDOS="" --PSEUDOS=""
``` ```
Ou avec un `docker-compose.yml` : Ou avec un `docker-compose.yml` :
@ -54,55 +60,10 @@ services:
build: https://git.kennel.ml/Anri/feurBot.git#main build: https://git.kennel.ml/Anri/feurBot.git#main
container_name: feurBot container_name: feurBot
environment: environment:
- CONSUMER_KEY=
- CONSUMER_SECRET=
- BEARER_TOKEN=
- TOKEN= - TOKEN=
- TOKEN_SECRET= - TOKEN_SECRET=
- CONSUMER_KEY=
- CONSUMER_SECRET=
- PSEUDOS= - PSEUDOS=
restart: unless-stopped restart: unless-stopped
``` ```
## Liste des mots
Certains mots peuvent servir de déclencheur sans être dans la liste,
example : `aussi` n'est pas dans la liste, mais en retirant `aus`,
on obtient `si`, qui est dans la liste.
| Mot | Réponse |
| ----------------------- | ----------------------------- |
| quoi | feur/feuse |
| oui | stiti/fi |
| non | bril |
| nan | cy |
| hein | deux/bécile |
| ci | tron/prine |
| con | combre/gelé/pas |
| ok | sur glace |
| ouais | stern |
| comment | tateur/tatrice/dant Cousteau |
| mais | on |
| fort | boyard |
| coup | teau |
| ça | pristi/von/perlipopette |
| bon | jour/soir (dépend de l'heure) |
| qui | wi/mono |
| sur | prise |
| pas | nini/steur/trimoine/té/stis |
| ka | pitaine/pitulation |
| fais | rtile |
| tant (ou autre syntaxe) | gente/tation |
| et | eint/ain |
| la | vabo/vande |
| tki | la |
| moi | tié/sson/sissure |
| toi | lette/ture |
| top | inambour |
| jour | nal |
| ya | hourt |
| yo | yo/ghourt |
| ni | cotine |
| re | pas/veil/tourne |
| quand | dide/tal/didat |
| sol | itaire |
| vois | ture |
| akhy | nator |

595
main.py
View file

@ -1,51 +1,48 @@
from datetime import datetime
from os import environ
from random import choice
from re import findall, sub
from dotenv import load_dotenv from dotenv import load_dotenv
from tweepy import Client, StreamingClient, StreamRule, Tweet, User, errors from os import environ
from tweepy import OAuth1UserHandler, API, Stream
from re import sub, findall
from random import choice
from datetime import datetime
from pytz import timezone
from queue import Queue
from json import loads
def load(variables) -> dict: def load(variables) -> dict:
"""Load environment variables""" """Load environment variables"""
keys = {} keys = {}
load_dotenv() # load .env file load_dotenv() # load .env file
for var in variables: for var in variables:
try: try:
if var == "VERBOSE": # check is VERBOSE is set if var == "VERBOSE": # check is VERBOSE is set
try: try:
if environ[var].lower() == "true": res = bool(environ[var])
res = True
except: except:
res = False # if not its False res = False # if not its False
elif var == "WHITELIST": # check if WHITELIST is set elif var == "WHITELIST": # check if WHITELIST is set
try: try:
res = list(set(environ[var].split(",")) - {""}) res = list(set(environ[var].split(",")) - {""})
except: except:
res = [] # if not its an empty list res = [] # if not its an empty list
elif var == "FORCELIST": # check if FORCELIST is set elif var == "FORCELIST": # check if FORCELIST is set
try: try:
res = list(set(environ[var].split(",")) - {""}) res = list(set(environ[var].split(",")) - {""})
except: except:
res = [] # if not its an empty list res = [] # if not its an empty list
else: else:
res = environ[var] res = environ[var]
if var == "PSEUDOS": if var == "PSEUDOS":
# create a list for the channels and remove blank channels and doubles res = list(set(res.split(",")) - {""}) # create a list for the channels and remove blank channels and doubles
res = list(set(res.split(",")) - {""})
keys[var] = res keys[var] = res
except KeyError: except KeyError:
print( print(f"Veuillez définir la variable d'environnement {var} (fichier .env supporté)")
f"Veuillez définir la variable d'environnement {var} (fichier .env supporté)")
exit(1) exit(1)
return keys return keys
def cleanTweet(tweet: str) -> str:
def cleanTweet(tweet: str) -> str | None:
"""Remove all unwanted elements from the tweet""" """Remove all unwanted elements from the tweet"""
# Convert to lower case # Convert to lower case
tweet = tweet.lower() tweet = tweet.lower()
# Remove URLs # Remove URLs
tweet = sub(r"(https?:\/\/\S+|www.\S+)", " ", tweet) tweet = sub(r"(https?:\/\/\S+|www.\S+)", " ", tweet)
# Check all hashtags # Check all hashtags
@ -56,7 +53,7 @@ def cleanTweet(tweet: str) -> str | None:
tweet = sub(r"#\S+", " ", tweet) tweet = sub(r"#\S+", " ", tweet)
else: else:
# Too much hashtags in the tweet -> so ignore it # Too much hashtags in the tweet -> so ignore it
return None return ""
# Remove usernames # Remove usernames
tweet = sub(r"@\S+", " ", tweet) tweet = sub(r"@\S+", " ", tweet)
# Remove everything who isn't a letter/number/space # Remove everything who isn't a letter/number/space
@ -66,173 +63,196 @@ def cleanTweet(tweet: str) -> str | None:
tweet = sub(r"\S+(?=si|ci)", " ", tweet) tweet = sub(r"\S+(?=si|ci)", " ", tweet)
# Remove key smashing in certains words # Remove key smashing in certains words
# uiii naaaan quoiiii noooon heiiin siiii # uiii naaaan quoiiii noooon heiiin siiii
tweet = sub( tweet = sub(r"(?<=ui)i+|(?<=na)a+(?<!n)|(?<=quoi)i+|(?<=no)o+(?<!n)|(?<=hei)i+(?<!n)|(?<=si)i+", "", tweet)
r"(?<=ui)i+|(?<=na)a+(?<!n)|(?<=quoi)i+|(?<=no)o+(?<!n)|(?<=hei)i+(?<!n)|(?<=si)i+", "", tweet)
return tweet.strip() return tweet.strip()
class Listener(Stream):
class Listener(StreamingClient):
"""Watch for tweets that match criteria in real-time""" """Watch for tweets that match criteria in real-time"""
def __init__( def __init__(
self, self,
bearer_token, consumer_key,
client: Client, consumer_secret,
access_token,
access_token_secret,
api: API = None,
users: list = None,
forcelist: list = None,
q = Queue()
): ):
super(Listener, self).__init__(bearer_token, wait_on_rate_limit=True) super(Listener, self).__init__(consumer_key, consumer_secret, access_token, access_token_secret)
self.client = client self.q = q
self.cache = {} self.api = api
self.accounts = [users, forcelist]
self.listOfFriendsID = getFriendsID(api, users) + getIDs(api, forcelist)
def on_connect(self): def on_connect(self):
print(f"Début du scroll sur Twitter...") if self.accounts[1] == []:
forcelist = "Aucun"
else:
forcelist = f"@{', @'.join(self.accounts[1])}"
print(f"Début du scroll sur Twitter avec les abonnements de @{', @'.join(self.accounts[0])} et ces comptes en plus : {forcelist} comme timeline...")
def _get_user(self, uid: int) -> User: def on_disconnect_message(notice):
"""Return username by ID, with cache support""" notice = notice["disconnect"]
# If not cached print(f"Déconnexion (code {notice['code']}).", end = " ")
if not uid in self.cache: if len(notice["reason"]) > 0:
# Fetch from Twitter print(f"Raison : {notice['reason']}")
self.cache[uid] = self.client.get_user(
id=uid, user_fields="protected", user_auth=True).data
# Return the user def on_status(self, status):
return self.cache[uid] json = status._json
# Verify the author of the tweet
if json["user"]["id"] in self.listOfFriendsID and json["user"]["screen_name"] not in keys["WHITELIST"]:
# Verify the age of the tweet
if seniority(json["created_at"]):
# Verify if the tweet isn't a retweet
if not hasattr(status, "retweeted_status"):
# Fetch the tweet
if "extended_tweet" in json:
tweet = cleanTweet(status.extended_tweet["full_text"])
else:
tweet = cleanTweet(status.text)
# Fetch the last word of the tweet
lastWord = tweet.split()[-1:][0]
if keys["VERBOSE"]:
infoLastWord = f"dernier mot : \"{lastWord}\"" if len(lastWord) > 0 else "tweet ignoré car trop de hashtags"
print(f"Tweet trouvé de {json['user']['screen_name']} ({infoLastWord})...", end = " ")
# Check if the last word found is a supported word
if lastWord in universalBase:
answer = None
def on_tweet(self, tweet: Tweet): # Check repetition
# Check if the tweet is not a retweet repetition = findall(r"di(\S+)", lastWord)
if not tweet.text.startswith("RT @"): if(len(repetition) > 0):
# Cancel if author of the first tweet in the conversation is in private # We need to repeat something...
if tweet.conversation_id and tweet.id != tweet.conversation_id: answer = repeater(repetition[0])
if keys["VERBOSE"]:
print("Thread...", end=" ") # Fetch an other adequate (better) response
base_tweet = self.client.get_tweet(id=tweet.conversation_id, tweet_fields="author_id", user_auth=True).data for mot in base.items():
# Sometimes Twitter don't give what we want if lastWord in mot[1]:
if hasattr(base_tweet, 'author_id'): # Handle specific case
base_author = self._get_user(base_tweet.author_id) if mot[0] == "bon":
# Check if account is in private mode # Between 7am and 5pm
if base_author.protected: if datetime.now().hour in range(7, 17):
if keys["VERBOSE"]: answer = answers[mot[0]][0] # jour
print("Auteur du premier tweet en privé, pas de réponses.") else:
return answer = answers[mot[0]][1] # soir
else:
# Normal answer
answer = answers[mot[0]]
if answer == None:
if keys["VERBOSE"]:
print(f"{errorMessage} Aucune réponse trouvée.")
# If an answer has been found
else:
if keys["VERBOSE"]:
print(f"Envoie d'un {answer[0]}...", end = " ")
try:
# Send the tweet with the answer
self.api.update_status(status = choice(answer), in_reply_to_status_id = json["id"], auto_populate_reply_metadata = True)
print(f"{json['user']['screen_name']} s'est fait {answer[0]} !")
except Exception as error:
error = loads(error.response.text)["errors"][0]
# https://developer.twitter.com/en/support/twitter-api/error-troubleshooting
show_error = True
if error["code"] == 385:
error["message"] = f"Tweet supprimé ou auteur ({json['user']['screen_name']}) en privé/bloqué."
show_error = False
# Show error only if relevant, always in verbose
if show_error or keys["VERBOSE"]:
print(f"{errorMessage[:-2]} ({error['code']}) ! {error['message']}")
else: else:
if keys["VERBOSE"]: if keys["VERBOSE"]:
print("Auteur du premier tweet en publique...", end=" ") print("Annulation car le dernier mot n'est pas intéressant.")
else:
# Can't check the status of the first tweet in the thread, ignoring for safety
if keys["VERBOSE"]:
print("Impossible de vérifier le status de l'auteur du fil.")
return
author = self._get_user(tweet.author_id)
# Clean the tweet
lastWord = cleanTweet(tweet.text)
# Log def do_stuff(self):
if keys["VERBOSE"]: """Loop for the Listener"""
infoLastWord = "dernier mot : " while True:
newline = "\n" self.q.get()
match lastWord: self.q.task_done()
case None:
infoLastWord += "tweet ignoré car trop de hashtags"
case w if len(w) == 0:
infoLastWord += "tweet pas intéressant"
case _:
infoLastWord += f"dernier mot : {lastWord.split()[-1:][0]}"
newline = ""
print(
f"Tweet trouvé de {author.username} ({infoLastWord})...{newline}", end=" ")
# Ignore a tweet
if lastWord == None or len(lastWord) == 0:
return
# Fetch the last word of the tweet
lastWord = lastWord.split()[-1:][0]
# Check if the last word found is a supported word
if lastWord in universalBase:
answer = None
# Check repetition
repetition = findall(r"di(\S+)", lastWord)
if len(repetition) > 0:
# We need to repeat something...
answer = repeater(repetition[0])
# Fetch an other adequate (better) response
for mot in base.items():
if lastWord in mot[1]:
# Handle specific case
if mot[0] == "bon":
# Between 7am and 5pm
if datetime.now().hour in range(7, 17):
answer = answers[mot[0]][0] # jour
else:
answer = answers[mot[0]][1] # soir
else:
# Normal answer
answer = answers[mot[0]]
# If no answer has been found
if answer == None:
if keys["VERBOSE"]:
print(f"{errorMessage} Aucune réponse trouvée.")
# If an answer has been found
else:
if keys["VERBOSE"]:
print(f"Envoie d'un {answer[0]}...", end=" ")
try:
# Send the tweet with the answer
self.client.create_tweet(
in_reply_to_tweet_id=tweet.id, text=choice(answer))
print(f"{author.username} s'est fait {answer[0]} !")
except errors.Forbidden:
if keys["VERBOSE"]:
print(
f"{errorMessage[:-2]} ! Tweet supprimé ou auteur ({author.username}) en privé/bloqué.")
else:
if keys["VERBOSE"]:
print("Annulation car le dernier mot n'est pas intéressant.")
def on_request_error(self, status_code): def on_request_error(self, status_code):
print(f"{errorMessage[:-2]} ({status_code}) !", end=" ") print(f"{errorMessage[:-2]} ({status_code}) !", end = " ")
match status_code: if status_code == 413:
case 420: if keys["VERBOSE"]:
if keys["VERBOSE"]: print("La liste des mots est trop longue (triggerWords).")
print("Déconnecter du flux.") elif status_code == 420:
case 429: if keys["VERBOSE"]:
if keys["VERBOSE"]: print("Déconnecter du flux.")
print("En attente de reconnexion...") else:
case _: print("\n")
# newline
print("")
return False return False
def repeater(word: str) -> str: def repeater(word: str) -> str:
"""Formating a word who need to be repeated""" """Formating a word who need to be repeated"""
# Remove first letter if the first letter is a "S" or a "T" # Remove first letter if the first letter is a "S" or a "T"
# Explanation: Trigger word for the repeater is "di" and sometimes it is # Explanation: Trigger word for the repeater is "di" and sometimes it is
# "dis", sometimes its "dit", that's why we need to remove this 2 letters # "dis", sometimes its "dit", that's why we need to remove this 2 letters
# from the final answer # from the final answer
if word[0] == "s" or word[0] == "t": if word[0] == 's' or word[0] == 't':
word = word[1:] word = word[1:]
# Random format from the base answer # Random format from the base answer
return createBaseAnswers(word) return createBaseAnswers(word)
def getFriendsID(api: API, users: list[str]) -> list:
def getFriends(client: Client, users: list[str]) -> list:
"""Get all friends of choosen users""" """Get all friends of choosen users"""
friends_list = [] liste = []
# Get IDs of the user's friends # Get IDs of the user's friends
for user in users: for user in users:
user_id = client.get_user(username=user, user_auth=True).data.id liste.extend(api.get_friend_ids(screen_name=user))
friends_list.extend(client.get_users_following( return list(set(liste))
id=user_id, user_auth=True))
return friends_list[0]
def getIDs(api: API, users: list[str]) -> list:
"""Get all the ID of users"""
liste = []
# Get IDs of the users
for user in users:
liste.append(api.get_user(screen_name=user)._json["id"])
return list(set(liste))
def seniority(date: str) -> bool:
"""Return True only if the given string date is less than one day old"""
# Convert string format to datetime format
datetimeObject = datetime.strptime(date, "%a %b %d %H:%M:%S +0000 %Y")
# Twitter give us an UTC time
datetimeObject = datetimeObject.replace(tzinfo = timezone("UTC"))
# time now in UTC minus the time we got to get the age of the date
age = datetime.now(timezone("UTC")) - datetimeObject
# False if older than a day, else True
return False if age.days >= 1 else True
def generateWords(array: list[str]) -> list:
"""
Retrieves all possible combinations for the given list and returns the result as a list
This is used for the filter in the stream (before calling the Listener::on_status)
"""
quoiListe = []
for text in array:
# Add all combinations
# Example for 'oui': ['OUI', 'OUi', 'OuI', 'Oui', 'oUI', 'oUi', 'ouI', 'oui']
#
# -> Depends on: from itertools import product
# -> Problem : Create a too long list (+1000 words, max is 400)
# -> Cf. https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/overview
#
# quoiListe.extend(list(map(''.join, product(*zip(text.upper(), text.lower())))))
if text.lower() not in quoiListe:
# Word in lowercase
quoiListe.append(text.lower())
if text.upper() not in quoiListe:
# Word in uppercase
quoiListe.append(text.upper())
if text.capitalize() not in quoiListe:
# Word capitalized
quoiListe.append(text.capitalize())
return quoiListe
def createBaseTrigger(lists: list[list]) -> list: def createBaseTrigger(lists: list[list]) -> list:
"""Merges all given lists into one""" """Merges all given lists into one"""
@ -241,7 +261,6 @@ def createBaseTrigger(lists: list[list]) -> list:
listing.extend(liste) listing.extend(liste)
return list(set(listing)) return list(set(listing))
def createBaseAnswers(word: str) -> list: def createBaseAnswers(word: str) -> list:
"""Generates default answers for a given word""" """Generates default answers for a given word"""
irritating_word = [ irritating_word = [
@ -251,7 +270,6 @@ def createBaseAnswers(word: str) -> list:
] ]
return [ return [
# Assuming the first element of this list is always word, don't change it
word, word,
f"({word})", f"({word})",
word.upper(), word.upper(),
@ -259,152 +277,47 @@ def createBaseAnswers(word: str) -> list:
f"{word}...", f"{word}...",
] ]
def start():
"""Start the bot"""
auth = OAuth1UserHandler(keys["CONSUMER_KEY"], keys["CONSUMER_SECRET"])
auth.set_access_token(keys["TOKEN"], keys["TOKEN_SECRET"])
def createClient(consumer_key, consumer_secret, access_token, access_token_secret) -> Client: api = API(auth)
"""Create a client for the Twitter API v2"""
client = Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret
)
if keys["VERBOSE"]: if keys["VERBOSE"]:
try: try:
print( api.verify_credentials()
f"Authentification réussie en tant que @{client.get_me().data.username}.\n") print(f"Authentification réussie en tant que", end = " ")
# Compte ignorés
if keys["WHITELIST"] == []:
whitelist = "Aucun"
else:
whitelist = f"@{', @'.join(keys['WHITELIST'])}"
print(f"Liste des comptes ignorés : {whitelist}.")
# Compte forcés
if keys["FORCELIST"] == []:
forcelist = "Aucun"
else:
forcelist = f"@{', @'.join(keys['FORCELIST'])}"
print(f"Liste des comptes forcés : {forcelist}.")
# Compte aux following suivis
if keys["PSEUDOS"] == []:
pseudos = "Aucun"
else:
pseudos = f"@{', @'.join(keys['PSEUDOS'])}"
print(
f"Les comptes suivis par ces comptes sont traqués : {pseudos}.\n")
print(
"Notez que si un compte est dans la whitelist, il sera dans tout les cas ignoré.\n")
except: except:
print("Erreur d'authentification.") print("Erreur d'authentification.")
exit(1) exit(1)
print(f"@{api.verify_credentials().screen_name}.")
return client if keys['WHITELIST'] == []:
whitelist = "Aucun"
def create_rules(tracked_users: list[str]) -> list[str]:
"""Create rules for tracking users, by respecting the twitter API policies"""
rules = []
# Repeating rules
repeat = "-is:retweet lang:fr ("
# Buffer
buffer = repeat
tracked_users.sort()
# Track users
for user in tracked_users:
# Check if the rule don't exceeds the maximum length of a rule (512)
# 5 is len of "from:"
# 1 is len for closing parenthesis
if len(buffer) + len(user) + 5 + 1 > 512:
rules.append(buffer[:-4] + ")")
buffer = repeat
buffer += f"from:{user} OR "
if len(buffer) > 0:
rules.append(buffer[:-4] + ")")
if len(rules) > 25:
raise BufferError("Too much rules.")
return rules
def start():
"""Start the bot"""
client = createClient(
keys["CONSUMER_KEY"],
keys["CONSUMER_SECRET"],
keys["TOKEN"],
keys["TOKEN_SECRET"],
)
# Only track specifics users
# Including users in forcelist and removing users in whitelist
tracked_users = [
i for i in [
user.data["username"] for user in getFriends(client, keys["PSEUDOS"])
] + keys["FORCELIST"] if i not in keys["WHITELIST"]
]
stream = Listener(keys["BEARER_TOKEN"], client)
# Gathering rules
rules = [rule for rule in create_rules(tracked_users)]
# Check if rules already exists
old_rules = stream.get_rules().data
old_rules_values = []
if old_rules:
old_rules_values = [rule.value for rule in old_rules]
need_changes = False
# Same amount of rules
if len(old_rules_values) == len(rules):
for rule in rules:
# Check if Twitter doesn't know the rule and change rules if needed
if rule not in old_rules_values:
need_changes = True
break
else: else:
need_changes = True whitelist = f"@{', @'.join(keys['WHITELIST'])}"
print(f"Liste des comptes ignorés : {whitelist}.")
if need_changes:
if keys["VERBOSE"]:
print("Changes needed... ", end=" ")
# Clean old rules
if old_rules:
if keys["VERBOSE"]:
print("deleting old rules... ", end=" ")
stream.delete_rules([rule.id for rule in old_rules])
# Add new rules
if keys["VERBOSE"]:
print("sending new filter to Twitter.")
stream.add_rules([StreamRule(rule) for rule in rules])
# Apply the filter
stream.filter(tweet_fields=["author_id", "conversation_id"])
stream = Listener(
consumer_key=keys["CONSUMER_KEY"],
consumer_secret=keys["CONSUMER_SECRET"],
access_token=keys["TOKEN"],
access_token_secret=keys["TOKEN_SECRET"],
api=api,
users=keys["PSEUDOS"],
forcelist=keys["FORCELIST"]
)
stream.filter(track = triggerWords, languages = ["fr"], stall_warnings = True, threaded = True)
if __name__ == "__main__": if __name__ == "__main__":
""" """
TOKEN is the Access Token available in the Authentication Tokens section under the Access Token and Secret sub-heading TOKEN is the Access Token available in the Authentication Tokens section under Access Token and Secret sub-heading.
TOKEN_SECRET is the Access Token Secret available in the Authentication Tokens section under the Access Token and Secret sub-heading TOKEN_SECRET is the Access Token Secret available in the Authentication Tokens section under Access Token and Secret sub-heading.
CONSUMER_KEY is the API Key available in the Consumer Keys section under the API Key and Secret sub-heading CONSUMER_KEY is the API Key available in the Consumer Keys section.
CONSUMER_SECRET is the API Secret Key available in the Consumer Keys section under the API Key and Secret sub-heading CONSUMER_SECRET is the API Secret Key available in the Consumer Keys section.
BEARER_TOKEN is the Bearer Token available in the Authentication Tokens section under the Bearer Token sub-heading
-- --
PSEUDOS is a list of account you want to listen, all of his·er following (guys followed by PSEUDO) will be sniped PSEUDO is the PSEUDO of the account you want to listen to snipe.
WHITELSIT is a list of account who are protected from the bot
FORCELIST is a list of account who are targeted by the bot, if user is in the whitelist, he·r will be ignored
---
VERBOSE enable some debugs log
""" """
# Error message # Error message
errorMessage = "Une erreur survient !" errorMessage = "Une erreur survient !"
@ -452,62 +365,62 @@ if __name__ == "__main__":
# Answers for all the triggers (keys in lowercase) # Answers for all the triggers (keys in lowercase)
answers = { answers = {
"quoi": createBaseAnswers("feur") "quoi": createBaseAnswers("feur")
+ createBaseAnswers("feuse") + createBaseAnswers("feuse")
+ [ + [
"https://twitter.com/Myshawii/status/1423219640025722880/video/1", "https://twitter.com/Myshawii/status/1423219640025722880/video/1",
"https://twitter.com/Myshawii/status/1423219684552417281/video/1", "https://twitter.com/Myshawii/status/1423219684552417281/video/1",
"feur (-isson -ictalope -diatre -uil)", "feur (-isson -ictalope -diatre -uil)",
"https://twitter.com/Myshawii/status/1455469162202075138/video/1", "https://twitter.com/Myshawii/status/1455469162202075138/video/1",
"https://twitter.com/Myshawii/status/1552026689101860865/video/1", "https://twitter.com/Myshawii/status/1552026689101860865/video/1",
"https://twitter.com/Myshawii/status/1553112547678720001/photo/1" "https://twitter.com/Myshawii/status/1553112547678720001/photo/1"
], ],
"oui": createBaseAnswers("stiti") "oui": createBaseAnswers("stiti")
+ createBaseAnswers("fi"), + createBaseAnswers("fi"),
"non": createBaseAnswers("bril"), "non": createBaseAnswers("bril"),
"nan": createBaseAnswers("cy"), "nan": createBaseAnswers("cy"),
"hein": createBaseAnswers("deux") "hein": createBaseAnswers("deux")
+ createBaseAnswers("bécile") + createBaseAnswers("bécile")
+ [ + [
"2" "2"
], ],
"ci": createBaseAnswers("tron") "ci": createBaseAnswers("tron")
+ createBaseAnswers("prine"), + createBaseAnswers("prine"),
"con": createBaseAnswers("combre") "con": createBaseAnswers("combre")
+ createBaseAnswers("gelé") + createBaseAnswers("gelé")
+ createBaseAnswers("pas"), + createBaseAnswers("pas"),
"ok": createBaseAnswers("sur glace"), "ok": createBaseAnswers("sur glace"),
"ouais": createBaseAnswers("stern"), "ouais": createBaseAnswers("stern"),
"comment": createBaseAnswers("tateur") "comment": createBaseAnswers("tateur")
+ createBaseAnswers("tatrice") + createBaseAnswers("tatrice")
+ createBaseAnswers("dant Cousteau"), + createBaseAnswers("dant Cousteau"),
"mais": createBaseAnswers("on") "mais": createBaseAnswers("on")
+ [ + [
"on (-dulation)" "on (-dulation)"
], ],
"fort": createBaseAnswers("boyard") "fort": createBaseAnswers("boyard")
+ [ + [
"boyard (-ennes)" "boyard (-ennes)"
], ],
"coup": createBaseAnswers("teau"), "coup": createBaseAnswers("teau"),
"ça": createBaseAnswers("perlipopette") "ça": createBaseAnswers("perlipopette")
+ createBaseAnswers("von") + createBaseAnswers("von")
+ createBaseAnswers("pristi") + createBaseAnswers("pristi")
+ [ + [
"pristi (-gnasse)" "pristi (-gnasse)"
], ],
"bon": [ "bon": [
createBaseAnswers("jour"), createBaseAnswers("jour"),
@ -515,38 +428,38 @@ if __name__ == "__main__":
], ],
"qui": createBaseAnswers("wi") "qui": createBaseAnswers("wi")
+ createBaseAnswers("mono"), + createBaseAnswers("mono"),
"sur": createBaseAnswers("prise"), "sur": createBaseAnswers("prise"),
"pas": createBaseAnswers("nini") "pas": createBaseAnswers("nini")
+ createBaseAnswers("steur") + createBaseAnswers("steur")
+ createBaseAnswers("trimoine") + createBaseAnswers("trimoine")
+ createBaseAnswers("") + createBaseAnswers("")
+ createBaseAnswers("stis"), + createBaseAnswers("stis"),
"ka": createBaseAnswers("pitaine") "ka": createBaseAnswers("pitaine")
+ createBaseAnswers("pitulation"), + createBaseAnswers("pitulation"),
"fais": createBaseAnswers("rtile"), "fais": createBaseAnswers("rtile"),
"tant": createBaseAnswers("gente") "tant": createBaseAnswers("gente")
+ createBaseAnswers("tation"), + createBaseAnswers("tation"),
"et": createBaseAnswers("eint") "et": createBaseAnswers("eint")
+ createBaseAnswers("ain"), + createBaseAnswers("ain"),
"la": createBaseAnswers("vabo") "la": createBaseAnswers("vabo")
+ createBaseAnswers("vande"), + createBaseAnswers("vande"),
"tki": createBaseAnswers("la"), "tki": createBaseAnswers("la"),
"moi": createBaseAnswers("tié") "moi": createBaseAnswers("tié")
+ createBaseAnswers("sson") + createBaseAnswers("sson")
+ createBaseAnswers("sissure"), + createBaseAnswers("sissure"),
"toi": createBaseAnswers("lette") "toi": createBaseAnswers("lette")
+ createBaseAnswers("ture"), + createBaseAnswers("ture"),
"top": createBaseAnswers("inambour"), "top": createBaseAnswers("inambour"),
@ -555,17 +468,17 @@ if __name__ == "__main__":
"ya": createBaseAnswers("hourt"), "ya": createBaseAnswers("hourt"),
"yo": createBaseAnswers("ghourt") "yo": createBaseAnswers("ghourt")
+ createBaseAnswers("yo"), + createBaseAnswers("yo"),
"ni": createBaseAnswers("cotine"), "ni": createBaseAnswers("cotine"),
"re": createBaseAnswers("pas") "re": createBaseAnswers("pas")
+ createBaseAnswers("veil") + createBaseAnswers("veil")
+ createBaseAnswers("tourne"), + createBaseAnswers("tourne"),
"quand": createBaseAnswers("dide") "quand": createBaseAnswers("dide")
+ createBaseAnswers("tal") + createBaseAnswers("tal")
+ createBaseAnswers("didat"), + createBaseAnswers("didat"),
"sol": createBaseAnswers("itaire"), "sol": createBaseAnswers("itaire"),
@ -577,9 +490,11 @@ if __name__ == "__main__":
# List of all the trigger words # List of all the trigger words
universalBase = createBaseTrigger(list(base.values())) universalBase = createBaseTrigger(list(base.values()))
# List of all the triggers words's variations
triggerWords = generateWords(universalBase)
# Loading environment variables # Loading environment variables
keys = load(["TOKEN", "TOKEN_SECRET", "CONSUMER_KEY", "CONSUMER_SECRET", keys = load(["TOKEN", "TOKEN_SECRET", "CONSUMER_KEY", "CONSUMER_SECRET", "PSEUDOS", "VERBOSE", "WHITELIST", "FORCELIST"])
"BEARER_TOKEN", "PSEUDOS", "VERBOSE", "WHITELIST", "FORCELIST"])
# Start the bot # Start the bot
start() start()