or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

facebook-upload.mdindex.mdtelegram-bot.mdtiktok-api.mdvideo-processing.md

telegram-bot.mddocs/

0

# Telegram Bot

1

2

Complete Telegram bot implementation providing remote control interface for TikTok video downloading and Facebook Reels uploading. Features user rate limiting, download statistics tracking, and command handling for seamless remote operation.

3

4

## Capabilities

5

6

### Bot Initialization

7

8

Setup and configuration for the Telegram bot instance.

9

10

```javascript { .api }

11

/**

12

* Create and configure Telegram bot instance

13

* Requires BOT_TOKEN environment variable

14

*/

15

const bot = new TeleBot({

16

token: process.env.BOT_TOKEN

17

});

18

19

/**

20

* Start the bot and begin listening for messages

21

*/

22

bot.start(): void;

23

```

24

25

**Usage Examples:**

26

27

```javascript

28

import TeleBot from 'telebot';

29

import dotenv from 'dotenv';

30

31

dotenv.config();

32

33

// Initialize bot with token from environment

34

const bot = new TeleBot({

35

token: process.env.BOT_TOKEN

36

});

37

38

// Start bot

39

bot.start();

40

console.log('Bot is running...');

41

```

42

43

### User Statistics Management

44

45

Track user download activity and enforce daily limits.

46

47

```javascript { .api }

48

/**

49

* Update download statistics for a user

50

* @param userId - Telegram user ID

51

*/

52

function updateUserStats(userId: number): void;

53

54

/**

55

* Check if user can download (within daily limit)

56

* @param userId - Telegram user ID

57

* @returns Boolean indicating if user can download

58

*/

59

function canUserDownload(userId: number): boolean;

60

61

/** Maximum downloads allowed per user per day */

62

const MAX_DOWNLOADS_PER_DAY: number = 5;

63

64

/** User statistics storage */

65

const userStats: Map<number, UserStats>;

66

67

interface UserStats {

68

/** Date of downloads (string format) */

69

date: string;

70

/** Number of downloads on this date */

71

count: number;

72

}

73

```

74

75

**Usage Examples:**

76

77

```javascript

78

// Check if user can download

79

const userId = 12345;

80

if (canUserDownload(userId)) {

81

// Process download

82

await handleTikTokUrl(msg, url);

83

updateUserStats(userId);

84

} else {

85

await bot.sendMessage(msg.chat.id, `You've reached the daily limit of ${MAX_DOWNLOADS_PER_DAY} downloads.`);

86

}

87

88

// Check user statistics

89

const stats = userStats.get(userId);

90

if (stats) {

91

console.log(`User ${userId} has ${stats.count} downloads on ${stats.date}`);

92

}

93

```

94

95

### Bot Commands

96

97

Available bot commands and their handlers.

98

99

```javascript { .api }

100

/**

101

* Handle start and help commands

102

* Shows welcome message and usage instructions

103

*/

104

bot.on(['/start', '/help'], (msg) => void);

105

106

/**

107

* Handle stats command

108

* Shows user's download statistics for current day

109

*/

110

bot.on('/stats', (msg) => void);

111

112

/**

113

* Handle text messages

114

* Processes TikTok URLs automatically

115

*/

116

bot.on('text', async (msg) => void);

117

```

118

119

**Usage Examples:**

120

121

```javascript

122

// User sends: /start

123

// Bot responds with:

124

`Welcome to TikTok Downloader Bot!

125

126

Commands:

127

/start or /help - Show this help message

128

/stats - Show your download statistics

129

130

To download a TikTok video, simply send the TikTok URL to the bot.

131

132

Note: You can download up to 5 videos per day.`

133

134

// User sends: /stats

135

// Bot responds with:

136

`Today (2023-09-05) you've downloaded 3 videos.`

137

// or

138

`You haven't downloaded any videos today.`

139

```

140

141

### Video Download Handling

142

143

Core functionality for processing TikTok URLs sent via bot messages.

144

145

```javascript { .api }

146

/**

147

* Download TikTok video with progress tracking and visual progress bar

148

* @param url - TikTok video URL

149

* @param outputPath - Local file path to save video

150

* @returns Promise resolving when download completes

151

* @throws Error if TikTok API fails or video unavailable

152

*/

153

async function downloadTikTokVideo(url: string, outputPath: string): Promise<void>;

154

155

/**

156

* Complete workflow for processing TikTok URL from Telegram message

157

* Includes rate limiting, download, upload, and cleanup

158

* @param msg - Telegram message object containing user and chat info

159

* @param url - Extracted TikTok URL to process

160

* @returns Promise resolving when processing completes

161

*/

162

async function handleTikTokUrl(msg: TelegramMessage, url: string): Promise<void>;

163

```

164

165

**Usage Examples:**

166

167

```javascript

168

// Complete workflow when user sends TikTok URL: https://vm.tiktok.com/ZSFxxxxxx/

169

// Bot automatically:

170

// 1. Checks user download limit (5 per day)

171

// 2. Sends "Processing..." reply message

172

// 3. Calls TiktokDL to get video metadata

173

// 4. Downloads video with progress bar using axios stream

174

// 5. Calls ReelsUpload with video filename and extracted caption

175

// 6. Sends success/failure message to user

176

// 7. Updates user statistics

177

// 8. Cleans up temporary files with fs.unlinkSync

178

179

// Internal download implementation

180

const outputPath = './download/video123.mp4';

181

try {

182

const result = await TiktokDL(url);

183

const video = result.result.video[0]; // First video URL

184

const response = await axios({

185

url: video,

186

method: 'GET',

187

responseType: 'stream'

188

});

189

190

// Progress bar setup

191

const totalLength = response.headers['content-length'];

192

const progressBar = new ProgressBar(progressTemplate, {

193

width: 40,

194

complete: '<',

195

incomplete: '•',

196

total: parseInt(totalLength)

197

});

198

199

await downloadTikTokVideo(url, outputPath);

200

} catch (error) {

201

console.error('Download failed:', error);

202

}

203

```

204

205

### Message Processing

206

207

Automatic URL detection and processing from user messages.

208

209

```javascript { .api }

210

/** Regular expression for detecting TikTok URLs in messages */

211

const tiktokRegex: RegExp = /https?:\/\/(?:m|www|vm|vt)?\.?tiktok\.com\/\S+/;

212

213

/** Configuration constants */

214

const MAX_DOWNLOADS_PER_DAY: number = 5;

215

const userStats: Map<number, UserStats>;

216

217

interface TelegramMessage {

218

/** Message text content */

219

text: string;

220

/** Sender information */

221

from: {

222

id: number;

223

// ... other Telegram user properties

224

};

225

/** Chat information */

226

chat: {

227

id: number;

228

// ... other Telegram chat properties

229

};

230

/** Message ID for replies */

231

message_id: number;

232

}

233

```

234

235

**URL Detection Examples:**

236

237

```javascript

238

// Supported URL formats

239

const supportedUrls = [

240

'https://www.tiktok.com/@user/video/123',

241

'https://vm.tiktok.com/ZSFxxxxxx/',

242

'https://vt.tiktok.com/ZSFxxxxxx/',

243

'https://m.tiktok.com/v/123.html',

244

'https://tiktok.com/@user/video/123'

245

];

246

247

// All formats are automatically detected and processed

248

```

249

250

## Bot Workflow

251

252

Complete processing workflow when user sends TikTok URL:

253

254

1. **URL Detection**: Extract TikTok URL from message using regex

255

2. **Rate Limit Check**: Verify user hasn't exceeded daily download limit

256

3. **Processing Message**: Send "Processing..." reply to user

257

4. **Video Download**: Use TiktokDL to get video metadata and download file

258

5. **Facebook Upload**: Upload video to Facebook Reels with extracted caption

259

6. **Result Notification**: Send success/failure message to user

260

7. **Statistics Update**: Increment user's daily download count

261

8. **Cleanup**: Remove temporary video file

262

263

## Configuration Requirements

264

265

### Environment Variables

266

267

```javascript { .api }

268

/** Bot token from BotFather */

269

process.env.BOT_TOKEN: string;

270

```

271

272

### Required Files and Setup

273

274

**Environment Configuration:**

275

- `.env` file with `BOT_TOKEN=your_telegram_bot_token`

276

- `config.json` with `{"tokenBOT": "your_token"}` (alternative to .env)

277

278

**Facebook Integration:**

279

- `cookies.json` with exported Facebook session cookies

280

- Valid Facebook account with Reels creation permissions

281

282

**File System:**

283

- `download/` directory for temporary file storage (auto-created)

284

- Write permissions for video file management

285

286

**External Dependencies:**

287

- Chrome/Chromium browser for Puppeteer

288

- FFmpeg installed for video conversion (if used)

289

290

**Bot Setup Process:**

291

1. Create bot with [@BotFather](https://t.me/BotFather) on Telegram

292

2. Copy bot token to `.env` or `config.json`

293

3. Export Facebook cookies using browser extension

294

4. Run `node telebot.js` to start bot

295

5. Send `/start` to bot to verify functionality

296

297

## Error Handling

298

299

The bot includes comprehensive error handling for various scenarios:

300

301

**Rate Limiting**:

302

```javascript

303

// User exceeds daily limit

304

`You've reached the daily limit of 5 downloads.`

305

```

306

307

**Processing Errors**:

308

```javascript

309

// General processing failure

310

`An error occurred: ${error.message}`

311

312

// TikTok API failures

313

// When TiktokDL returns error status

314

if (result.status === 'error') {

315

// Handle specific TikTok API errors

316

}

317

```

318

319

**Upload Failures**:

320

```javascript

321

// Facebook upload fails

322

`Upload failed: ${upload.message}`

323

324

// Specific upload error messages (in Indonesian)

325

"Video Gagal di publish!" // "Video failed to publish!"

326

"INFO: Session tidak ditemukan..." // "INFO: Session not found..."

327

```

328

329

**Network and File Errors**:

330

```javascript

331

// Download failures

332

"Error downloading video: ${error.message}"

333

334

// File system errors during cleanup

335

// fs.unlinkSync may throw if file doesn't exist or permissions issue

336

try {

337

fs.unlinkSync(outputPath);

338

} catch (cleanupError) {

339

// Non-critical cleanup failure

340

}

341

```

342

343

## Bot Statistics

344

345

The bot maintains daily download statistics for each user:

346

347

- Automatic reset at midnight

348

- Per-user tracking via Telegram user ID

349

- Configurable daily limits

350

- Persistent across bot restarts (in-memory storage)