import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# Fonction pour collecter les tweets en rapport avec la marque
def collect_tweets(api, brand_name, count=100):
    tweets = []
    query = f"{brand_name} -filter:retweets"  # Ne pas inclure les retweets dans les résultats
    for tweet in tweepy.Cursor(api.search, q=query, lang="fr").items(count):
        tweets.append(tweet.text)
    return tweets

# Fonction pour effectuer l'analyse de sentiment
def analyze_sentiment(text):
    analysis = TextBlob(text)
    return analysis.sentiment.polarity

# Fonction pour créer un nuage de mots
def create_wordcloud(text):
    wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()

# Configuration de l'API Twitter
consumer_key = '**'
consumer_secret = '**'
access_token = '*-*'
access_token_secret = '**'

auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)

# Collecte de tweets en rapport avec la marque
brand_name = "Votre_marque"
tweets = collect_tweets(api, brand_name, count=100)

# Analyse de sentiment
sentiments = [analyze_sentiment(tweet) for tweet in tweets]

# Création d'un nuage de mots basé sur les tweets positifs
positive_tweets = ' '.join([tweets[i] for i in range(len(tweets)) if sentiments[i] > 0])
create_wordcloud(positive_tweets)

# Création d'un nuage de mots basé sur les tweets négatifs
negative_tweets = ' '.join([tweets[i] for i in range(len(tweets)) if sentiments[i] < 0])
create_wordcloud(negative_tweets)