Skip to content

Instantly share code, notes, and snippets.

@stesie
Created February 2, 2025 10:49
Show Gist options
  • Select an option

  • Save stesie/37406b103050e068018765d485c25aef to your computer and use it in GitHub Desktop.

Select an option

Save stesie/37406b103050e068018765d485c25aef to your computer and use it in GitHub Desktop.
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const { Pool } = require('pg');
// Telegram bot token
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
// OpenAI API key
const openaiApiKey = 'YOUR_OPENAI_API_KEY';
// Postgres database connection
const db = new Pool({
user: 'YOUR_DB_USERNAME',
host: 'YOUR_DB_HOST',
database: 'YOUR_DB_NAME',
password: 'YOUR_DB_PASSWORD',
port: 5432,
});
// Create a Telegram bot instance
const bot = new TelegramBot(token, { polling: true });
// Handle incoming messages
bot.on('message', async (msg) => {
if (msg.photo) {
// Get the photo file ID
const fileId = msg.photo[0].file_id;
// Download the photo
const photoUrl = await bot.getFileLink(fileId);
const photoResponse = await axios.get(photoUrl, { responseType: 'arraybuffer' });
const photoBuffer = photoResponse.data;
// Upload the photo to OpenAI API
const openaiResponse = await axios.post('https://api.openai.com/v1/images/generate', {
prompt: 'Read the gas meter value from the image',
image: photoBuffer.toString('base64'),
}, {
headers: {
'Authorization': `Bearer ${openaiApiKey}`,
'Content-Type': 'application/json',
},
});
// Extract the gas meter value from the OpenAI response
const gasMeterValue = openaiResponse.data.choices[0].text;
const regex = /^\d{5},\d{3}$/;
if (regex.test(gasMeterValue)) {
// Store the gas meter value in the Postgres database
const query = {
text: `INSERT INTO gas_meter_readings (reading) VALUES ($1) RETURNING *`,
values: [gasMeterValue],
};
const result = await db.query(query);
const readingId = result.rows[0].id;
// Return the gas meter value in the chat
bot.sendMessage(msg.chat.id, `Gas meter value: ${gasMeterValue}`);
} else {
bot.sendMessage(msg.chat.id, 'Invalid gas meter value');
}
} else {
bot.sendMessage(msg.chat.id, 'Please send a photo of the gas meter');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment