Created
August 31, 2022 18:21
-
-
Save salman0ansari/65fff346cfce477e20a256e034aeb274 to your computer and use it in GitHub Desktop.
quiz poster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv from 'csv-parser' | |
import { createReadStream } from 'fs' | |
import axios from 'axios' | |
// constants | |
const BOT_TOKEN = "BOT TOKEN HERE" | |
const CHANNEL_ID = -763513 // replace it with your group id | |
// function to read data from csv file and return it as an array | |
async function getData() { | |
const results = []; | |
return new Promise((resolve, reject) => { | |
try { | |
createReadStream('my.csv') | |
.pipe(csv()) | |
.on('data', (data) => results.push(data)) | |
.on('end', () => { | |
resolve(results) | |
}); | |
} catch (error) { | |
reject(error) | |
} | |
}) | |
} | |
// function to find answer index | |
function findAnswerIndex(obj) { | |
if (obj.quiz_type === 'match') { return "invalid quiz type" } | |
return new Promise((resolve) => { | |
const answer = obj.answer | |
const options = [obj.option_a, obj.option_b, obj.option_c, obj.option_d] | |
for (let i = 0; i < options.length; i++) { | |
if (options[i] === answer) | |
resolve(i) | |
} | |
}) | |
} | |
// function to get random element from array | |
function getRandomElement(arr) { | |
return arr[Math.floor(Math.random() * arr.length)]; | |
} | |
const csvData = await getData() | |
const obj = getRandomElement(csvData) | |
const answerIndex = await findAnswerIndex(obj) | |
const options = [obj.option_a, obj.option_b, obj.option_c, obj.option_d] | |
const uri = `https://api.telegram.org/bot${BOT_TOKEN}/sendPoll?chat_id=${CHANNEL_ID}&` + | |
`question=${obj.question}&options=${JSON.stringify(options)}&type=${'quiz'}&correct_option_id=${answerIndex}` + | |
`&is_anonymous=true` | |
const d = await axios(uri) | |
console.log(d.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment