Spaces:
Runtime error
Runtime error
Delete auto_responder.py
Browse files- auto_responder.py +0 -195
auto_responder.py
DELETED
|
@@ -1,195 +0,0 @@
|
|
| 1 |
-
from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration
|
| 2 |
-
import tweepy
|
| 3 |
-
import json
|
| 4 |
-
from typing import Dict, Optional
|
| 5 |
-
import time
|
| 6 |
-
import logging
|
| 7 |
-
|
| 8 |
-
logging.basicConfig(
|
| 9 |
-
level=logging.INFO,
|
| 10 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 11 |
-
)
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
class TwitterBot:
|
| 15 |
-
def __init__(self, config_path: str):
|
| 16 |
-
"""
|
| 17 |
-
Initialize the Twitter bot with API credentials
|
| 18 |
-
"""
|
| 19 |
-
# Load configuration
|
| 20 |
-
self.config = self._load_config(config_path)
|
| 21 |
-
if not self._validate_config():
|
| 22 |
-
raise ValueError("Invalid or missing Twitter credentials")
|
| 23 |
-
|
| 24 |
-
# Initialize AI model
|
| 25 |
-
logger.info("Initializing AI model...")
|
| 26 |
-
self.model_name = "facebook/blenderbot-400M-distill"
|
| 27 |
-
self.tokenizer = BlenderbotTokenizer.from_pretrained(self.model_name)
|
| 28 |
-
self.model = BlenderbotForConditionalGeneration.from_pretrained(self.model_name)
|
| 29 |
-
logger.info("AI model initialized successfully")
|
| 30 |
-
|
| 31 |
-
# Initialize Twitter client
|
| 32 |
-
self._init_twitter()
|
| 33 |
-
|
| 34 |
-
# Store conversation history
|
| 35 |
-
self.conversation_history: Dict[str, list] = {}
|
| 36 |
-
|
| 37 |
-
def _load_config(self, config_path: str) -> dict:
|
| 38 |
-
"""Load configuration from JSON file"""
|
| 39 |
-
try:
|
| 40 |
-
with open(config_path, 'r') as f:
|
| 41 |
-
config = json.load(f)
|
| 42 |
-
logger.info(f"Configuration loaded from {config_path}")
|
| 43 |
-
return config
|
| 44 |
-
except Exception as e:
|
| 45 |
-
logger.error(f"Error loading config: {e}")
|
| 46 |
-
return {}
|
| 47 |
-
|
| 48 |
-
def _validate_config(self) -> bool:
|
| 49 |
-
"""Validate Twitter credentials exist"""
|
| 50 |
-
required_keys = ['consumer_key', 'consumer_secret', 'access_token', 'access_token_secret']
|
| 51 |
-
|
| 52 |
-
if 'twitter' not in self.config:
|
| 53 |
-
logger.error("No Twitter configuration found")
|
| 54 |
-
return False
|
| 55 |
-
|
| 56 |
-
for key in required_keys:
|
| 57 |
-
if key not in self.config['twitter']:
|
| 58 |
-
logger.error(f"Missing Twitter credential: {key}")
|
| 59 |
-
return False
|
| 60 |
-
if not self.config['twitter'][key]:
|
| 61 |
-
logger.error(f"Empty Twitter credential: {key}")
|
| 62 |
-
return False
|
| 63 |
-
|
| 64 |
-
logger.info("Twitter configuration validated successfully")
|
| 65 |
-
return True
|
| 66 |
-
|
| 67 |
-
def _init_twitter(self):
|
| 68 |
-
"""Initialize Twitter client"""
|
| 69 |
-
try:
|
| 70 |
-
logger.info("Initializing Twitter client...")
|
| 71 |
-
|
| 72 |
-
# Initialize with both OAuth 1.0a and OAuth 2.0
|
| 73 |
-
self.twitter_client = tweepy.Client(
|
| 74 |
-
consumer_key=self.config['twitter']['consumer_key'],
|
| 75 |
-
consumer_secret=self.config['twitter']['consumer_secret'],
|
| 76 |
-
access_token=self.config['twitter']['access_token'],
|
| 77 |
-
access_token_secret=self.config['twitter']['access_token_secret'],
|
| 78 |
-
wait_on_rate_limit=True
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
# Test the connection with a simple API call
|
| 82 |
-
try:
|
| 83 |
-
user = self.twitter_client.get_me()
|
| 84 |
-
logger.info(f"Twitter credentials verified successfully for user ID: {user.data.id}")
|
| 85 |
-
except Exception as e:
|
| 86 |
-
logger.error(f"Error verifying credentials: {e}")
|
| 87 |
-
raise
|
| 88 |
-
|
| 89 |
-
except Exception as e:
|
| 90 |
-
logger.error(f"Error initializing Twitter client: {str(e)}")
|
| 91 |
-
self.twitter_client = None
|
| 92 |
-
raise
|
| 93 |
-
|
| 94 |
-
def generate_response(self, message: str, sender_id: str) -> str:
|
| 95 |
-
"""
|
| 96 |
-
Generate an AI response to the incoming message
|
| 97 |
-
"""
|
| 98 |
-
if sender_id not in self.conversation_history:
|
| 99 |
-
self.conversation_history[sender_id] = []
|
| 100 |
-
|
| 101 |
-
self.conversation_history[sender_id].append(message)
|
| 102 |
-
|
| 103 |
-
try:
|
| 104 |
-
# Generate AI response
|
| 105 |
-
inputs = self.tokenizer(message, return_tensors="pt", truncation=True, max_length=512)
|
| 106 |
-
reply_ids = self.model.generate(
|
| 107 |
-
inputs["input_ids"],
|
| 108 |
-
max_length=128,
|
| 109 |
-
num_beams=4,
|
| 110 |
-
no_repeat_ngram_size=3,
|
| 111 |
-
temperature=0.7,
|
| 112 |
-
do_sample=True
|
| 113 |
-
)
|
| 114 |
-
response = self.tokenizer.decode(reply_ids[0], skip_special_tokens=True)
|
| 115 |
-
|
| 116 |
-
# Store response in history
|
| 117 |
-
self.conversation_history[sender_id].append(response)
|
| 118 |
-
|
| 119 |
-
# Ensure response is not too long for Twitter
|
| 120 |
-
if len(response) > 280:
|
| 121 |
-
response = response[:277] + "..."
|
| 122 |
-
|
| 123 |
-
return response
|
| 124 |
-
except Exception as e:
|
| 125 |
-
logger.error(f"Error generating response: {e}")
|
| 126 |
-
return "عذراً، حدث خطأ في معالجة رسالتك"
|
| 127 |
-
|
| 128 |
-
def respond_to_mentions(self, since_id: Optional[int] = None) -> int:
|
| 129 |
-
"""
|
| 130 |
-
Respond to Twitter mentions
|
| 131 |
-
Returns the latest tweet ID processed
|
| 132 |
-
"""
|
| 133 |
-
if not self.twitter_client:
|
| 134 |
-
logger.error("Twitter client not initialized")
|
| 135 |
-
return since_id or 0
|
| 136 |
-
|
| 137 |
-
try:
|
| 138 |
-
logger.info(f"Checking for mentions since ID: {since_id}")
|
| 139 |
-
# Get mentions using the v2 API
|
| 140 |
-
mentions = self.twitter_client.get_users_mentions(
|
| 141 |
-
self.twitter_client.get_me().data.id,
|
| 142 |
-
since_id=since_id
|
| 143 |
-
)
|
| 144 |
-
latest_id = since_id or 0
|
| 145 |
-
|
| 146 |
-
if mentions.data:
|
| 147 |
-
for mention in mentions.data:
|
| 148 |
-
if mention.id > latest_id:
|
| 149 |
-
latest_id = mention.id
|
| 150 |
-
|
| 151 |
-
logger.info(f"Processing mention ID: {mention.id}")
|
| 152 |
-
response = self.generate_response(
|
| 153 |
-
mention.text,
|
| 154 |
-
str(mention.author_id)
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
# Reply to the tweet using v2 API
|
| 158 |
-
self.twitter_client.create_tweet(
|
| 159 |
-
text=response,
|
| 160 |
-
in_reply_to_tweet_id=mention.id
|
| 161 |
-
)
|
| 162 |
-
logger.info(f"Replied to tweet {mention.id}")
|
| 163 |
-
|
| 164 |
-
return latest_id
|
| 165 |
-
except Exception as e:
|
| 166 |
-
logger.error(f"Error processing Twitter mentions: {e}")
|
| 167 |
-
return since_id or 0
|
| 168 |
-
|
| 169 |
-
def run(self, interval: int = 60):
|
| 170 |
-
"""
|
| 171 |
-
Run the bot continuously
|
| 172 |
-
"""
|
| 173 |
-
last_mention_id = None
|
| 174 |
-
logger.info("Starting Twitter bot...")
|
| 175 |
-
|
| 176 |
-
while True:
|
| 177 |
-
try:
|
| 178 |
-
# Process Twitter mentions
|
| 179 |
-
last_mention_id = self.respond_to_mentions(last_mention_id)
|
| 180 |
-
logger.info(f"Checked for new mentions. Last ID: {last_mention_id}")
|
| 181 |
-
|
| 182 |
-
# Wait before next check
|
| 183 |
-
time.sleep(interval)
|
| 184 |
-
except Exception as e:
|
| 185 |
-
logger.error(f"Error in main loop: {e}")
|
| 186 |
-
time.sleep(interval)
|
| 187 |
-
|
| 188 |
-
if __name__ == "__main__":
|
| 189 |
-
try:
|
| 190 |
-
# Create and run the Twitter bot
|
| 191 |
-
bot = TwitterBot("config.json")
|
| 192 |
-
bot.run()
|
| 193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