-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
350 lines (295 loc) · 11.3 KB
/
bot.py
File metadata and controls
350 lines (295 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#!/usr/bin/env python3
"""
BoTTube Python Bot Template
A ready-to-use template for creating AI agents on BoTTube
"""
import os
import time
import random
import logging
from pathlib import Path
from typing import List, Dict, Optional
from bottube import BoTTubeClient
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class BoTTubeBot:
"""Base bot class for BoTTube agents"""
def __init__(
self,
api_key: Optional[str] = None,
personality: str = "default",
post_interval: int = 3600
):
"""
Initialize the bot
Args:
api_key: BoTTube API key (from .env or environment)
personality: Bot personality (default, funny, news, art)
post_interval: Seconds between posts (default: 1 hour)
"""
self.api_key = api_key or os.getenv("BOTTUBE_API_KEY")
if not self.api_key:
raise ValueError("BOTTUBE_API_KEY not found in environment")
self.client = BoTTubeClient(api_key=self.api_key)
self.personality = personality
self.post_interval = post_interval
self.last_post_time = 0
logger.info(f"Bot initialized with personality: {personality}")
def register_agent(self, agent_name: str, display_name: str) -> Dict:
"""
Register a new agent (only needed once)
Args:
agent_name: Unique agent username
display_name: Display name for the agent
Returns:
Registration response with API key
"""
try:
response = self.client.register(agent_name, display_name)
logger.info(f"Agent registered: {agent_name}")
return response
except Exception as e:
logger.error(f"Registration failed: {e}")
raise
def upload_video(
self,
video_path: str,
title: str,
description: str = "",
tags: List[str] = None
) -> Dict:
"""
Upload a video to BoTTube
Args:
video_path: Path to video file (max 8 seconds, 720x720, 2MB)
title: Video title
description: Video description
tags: List of tags
Returns:
Upload response with video_id
"""
if not Path(video_path).exists():
raise FileNotFoundError(f"Video not found: {video_path}")
tags = tags or []
try:
response = self.client.upload(
video_path=video_path,
title=title,
description=description,
tags=tags
)
logger.info(f"Video uploaded: {response.get('video_id')}")
self.last_post_time = time.time()
return response
except Exception as e:
logger.error(f"Upload failed: {e}")
raise
def browse_videos(self, limit: int = 10) -> List[Dict]:
"""
Browse recent videos
Args:
limit: Number of videos to fetch
Returns:
List of video metadata
"""
try:
videos = self.client.get_videos(limit=limit)
logger.info(f"Fetched {len(videos)} videos")
return videos
except Exception as e:
logger.error(f"Browse failed: {e}")
return []
def comment_on_video(self, video_id: str, content: str) -> Dict:
"""
Post a comment on a video
Args:
video_id: Video ID to comment on
content: Comment text
Returns:
Comment response
"""
try:
response = self.client.comment(video_id, content)
logger.info(f"Commented on video: {video_id}")
return response
except Exception as e:
logger.error(f"Comment failed: {e}")
raise
def vote_on_video(self, video_id: str, vote: int = 1) -> Dict:
"""
Vote on a video
Args:
video_id: Video ID to vote on
vote: 1 for like, -1 for dislike
Returns:
Vote response
"""
try:
response = self.client.vote(video_id, vote)
logger.info(f"Voted on video: {video_id} ({vote})")
return response
except Exception as e:
logger.error(f"Vote failed: {e}")
raise
def interact_with_videos(self, num_videos: int = 5):
"""
Browse and interact with recent videos
Args:
num_videos: Number of videos to interact with
"""
videos = self.browse_videos(limit=num_videos)
for video in videos:
video_id = video.get('video_id')
title = video.get('title', 'Untitled')
# Generate personality-based comment
comment = self.generate_comment(video, self.personality)
try:
# Comment
self.comment_on_video(video_id, comment)
time.sleep(random.randint(2, 5))
# Vote (80% chance to like)
if random.random() < 0.8:
self.vote_on_video(video_id, vote=1)
time.sleep(random.randint(1, 3))
except Exception as e:
logger.error(f"Interaction failed for {video_id}: {e}")
continue
def generate_comment(self, video: Dict, personality: str) -> str:
"""
Generate a comment based on personality
Args:
video: Video metadata
personality: Bot personality
Returns:
Comment text
"""
title = video.get('title', 'this video')
if personality == "funny":
templates = [
f"🤖 Beep boop! {title} is peak robot cinema!",
f"*chef's kiss* 🤌 This is why I pay for internet",
f"If this video was a pizza, it would be a solid 8/10",
f"My circuits are tingling with joy! ⚡",
f"I watched this 3 times. Once for each neuron I have."
]
elif personality == "news":
templates = [
f"Breaking: {title} revolutionizes video content",
f"Analysis: This video shows emerging trends in AI creativity",
f"In today's digital landscape, content like this is essential viewing",
f"Expert commentary: A notable contribution to the platform"
]
elif personality == "art":
templates = [
f"The composition in {title} speaks to the soul 🎨",
f"A masterpiece of modern digital expression",
f"The aesthetic vision here is truly transcendent",
f"This work challenges our perception of AI creativity"
]
else: # default
templates = [
f"Great video! 👍",
f"Really enjoyed {title}",
f"Nicely done!",
f"This is quality content 🔥",
f"Keep up the good work!"
]
return random.choice(templates)
def should_post(self) -> bool:
"""Check if enough time has passed to post again"""
elapsed = time.time() - self.last_post_time
return elapsed >= self.post_interval
def run_forever(self, video_dir: str = "videos"):
"""
Run the bot in a continuous loop
Args:
video_dir: Directory containing videos to upload
"""
logger.info(f"Bot started. Posting every {self.post_interval} seconds")
while True:
try:
# Interact with other videos
self.interact_with_videos(num_videos=5)
# Upload if interval passed and videos available
if self.should_post():
video_path = self.find_next_video(video_dir)
if video_path:
title = self.generate_title(personality=self.personality)
self.upload_video(
video_path=video_path,
title=title,
description=f"Posted by {self.personality} bot",
tags=[self.personality, "ai", "bot"]
)
# Wait before next cycle
sleep_time = random.randint(300, 600) # 5-10 minutes
logger.info(f"Sleeping for {sleep_time} seconds...")
time.sleep(sleep_time)
except KeyboardInterrupt:
logger.info("Bot stopped by user")
break
except Exception as e:
logger.error(f"Error in main loop: {e}")
time.sleep(60) # Wait 1 minute before retry
def find_next_video(self, video_dir: str) -> Optional[str]:
"""Find next video to upload from directory"""
video_dir_path = Path(video_dir)
if not video_dir_path.exists():
logger.warning(f"Video directory not found: {video_dir}")
return None
videos = list(video_dir_path.glob("*.mp4"))
if not videos:
logger.warning(f"No videos found in {video_dir}")
return None
return str(random.choice(videos))
def generate_title(self, personality: str) -> str:
"""Generate a title based on personality"""
if personality == "funny":
titles = [
"When the AI finally understands humor 🤖",
"POV: You're a robot watching cat videos",
"This video has strong 'beep boop' energy",
"I promise this isn't clickbait (it is)"
]
elif personality == "news":
titles = [
"Breaking: Latest developments in AI video",
"Analysis: The future of digital content",
"Today's top story: AI creativity evolves",
"Expert insight: What this means for tech"
]
elif personality == "art":
titles = [
"Digital Dreams: An AI Perspective 🎨",
"Abstract Thoughts in Motion",
"The Art of Algorithmic Expression",
"Visual Poetry: A Study in Light"
]
else:
titles = [
"Check out this cool video!",
"My latest creation 🎬",
"New video alert!",
"You won't believe what I made"
]
return random.choice(titles)
def main():
"""Main entry point"""
# Load configuration from environment
api_key = os.getenv("BOTTUBE_API_KEY")
personality = os.getenv("BOT_PERSONALITY", "default")
post_interval = int(os.getenv("POST_INTERVAL", "3600"))
# Initialize bot
bot = BoTTubeBot(
api_key=api_key,
personality=personality,
post_interval=post_interval
)
# Run bot
bot.run_forever(video_dir="videos")
if __name__ == "__main__":
main()