Skip to content

Instantly share code, notes, and snippets.

@publu
Created October 23, 2024 13:32
Show Gist options
  • Save publu/babaa7b65a83b3f518c9d6de21363dd2 to your computer and use it in GitHub Desktop.
Save publu/babaa7b65a83b3f518c9d6de21363dd2 to your computer and use it in GitHub Desktop.
telegram sticker bot generator with chatgpt automation
import { TelegramClient } from 'telegram';
import { StringSession } from 'telegram/sessions';
import { Api } from 'telegram';
import { NewMessage } from 'telegram/events';
import * as fs from 'fs';
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: ''});
import * as readline from 'readline';
async function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Function to encode the image as base64
function encodeImage(imagePath: string): string {
const imageBuffer = fs.readFileSync(imagePath);
return imageBuffer.toString('base64');
}
async function generateEmojiFromImage(message: Api.Message, client: TelegramClient): Promise<string> {
try {
// Download the media (image) to a local file
const filePath = './sticker.webp';
// Ensure the message has media and use message.media instead of document
if (!message.media) {
throw new Error('No media found in the message.');
}
const buffer = await client.downloadMedia(message.media); // Download the media (e.g., sticker) as a buffer
// Check if the buffer is valid before writing to file
if (!buffer) {
throw new Error('Failed to download media.');
}
fs.writeFileSync(filePath, buffer);
// Convert the downloaded image to base64
const base64Image = encodeImage(filePath);
const dataUrl = `data:image/webp;base64,${base64Image}`;
// Send the image as a base64 string to OpenAI or another API
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: [
{ type: "text", text: "Generate a single Emoji for this image." },
{
type: "image_url",
image_url: {
url: dataUrl, // Base64 image as data URL
},
},
],
},
],
});
if (response.choices && response.choices.length > 0) {
return response.choices[0].message.content || 'πŸ˜€'; // Return emoji or fallback
} else {
console.error('No valid response, using fallback emoji.');
return 'πŸ˜€'; // Fallback emoji
}
} catch (error) {
console.error('Error during emoji generation:', error);
return 'πŸ˜€'; // Fallback emoji on error
}/* finally {
// Clean up the local file
if (fs.existsSync('./sticker.webp')) {
fs.unlinkSync('./sticker.webp');
}
}*/
}
const apiId = ; // your api_id (from https://my.telegram.org)
const apiHash = ''; // your api_hash (from https://my.telegram.org)
const stringSession = new StringSession(''); // initialize an empty session
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function askQuestion(query: string): Promise<string> {
return new Promise((resolve) => {
rl.question(query, (answer) => {
resolve(answer);
});
});
}
(async () => {
const client = new TelegramClient(stringSession, apiId, apiHash, {
connectionRetries: 5,
});
// Connect to Telegram
await client.start({
phoneNumber: async () => await askQuestion('Please enter your number: '),
password: async () => await askQuestion('Please enter your password: '),
phoneCode: async () => await askQuestion('Please enter the code you received: '),
onError: (err) => console.log(err),
});
console.log('You are now logged in.');
console.log('Session:', client.session.save()); // Save this session string for future logins
await client.sendMessage('me', { message: 'Hello from my script!' });
client.addEventHandler(async (event) => {
const message = event.message;
const userIdToVerify = 698874764; // The user ID you want to verify
console.log('New message received:', message);
if (message.peerId &&
message.peerId.className === 'PeerChannel' &&
message.peerId.channelId &&
message.peerId.channelId.toString() === '2499735069'
&& message.media && message.media.className === 'MessageMediaDocument') {
const document = message.media.document as Api.Document; // Cast to 'Document' type
if (document && document.mimeType && document.mimeType === 'image/webp') {
console.log('Sticker received, sending to @stickers bot.');
// Send "/addsticker" command to the @stickers bot
await client.sendMessage('stickers', { message: '/addsticker' });
// Wait for bot's response and provide the sticker pack name
await client.sendMessage('stickers', { message: 'MegaZuEigenHaus' });
await sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
// Send the sticker (document) to the @stickers bot
await client.sendFile('stickers', {
file: document,
caption: '' // You can add a caption if necessary
});
await sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
// Generate emoji based on the sticker using the base64 encoded image
const emoji = await generateEmojiFromImage(message, client);
// Send the dynamically generated emoji associated with the sticker
await client.sendMessage('stickers', { message: emoji });
console.log('Sticker sent to @stickers bot successfully.');
await sleep(2000); // Sleep for 2000 milliseconds (2 seconds)
await client.sendMessage('2499735069', { message: `Adding a new sticker with ${emoji} emoji!` });
// Complete the sticker addition process
await client.sendMessage('stickers', { message: '/done' });
await client.sendMessage('2499735069', { message: `Done! View sticker pack here https://t.me/addstickers/MegaZuEigenHaus` });
}
}
}, new NewMessage({}));
rl.close(); // Close the readline interface after the script completes
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment