Telegram bot won't respond even doe webhook is set - telegram

The code for the bot is currently hosted on a Cloudflare worker, and there are no errors being reported from that end. Additionally, upon investigation of the Botfather side, everything seems to be functioning normally as well. However, despite attempting various solutions such as changing bots, tokens, and chat groups, the issue remains.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const { pathname } = new URL(request.url)
if (pathname === '/') {
return new Response('Hello! This is a Telegram bot. Send me a message.')
}
const { text } = await request.json()
if (text.startsWith('/start')) {
return new Response('Welcome to the bot! Use the /help command to see available options.')
} else if (text.startsWith('/help')) {
return new Response('Available commands:\n/scrape - scrapes videos from the specified website and sends them to the Telegram chat.\n/<example> - scrapes posts from the specified website and sends them to the Telegram chat.')
} else if (text.startsWith('/scrape')) {
const videoUrl = await scrapeVideoUrl('<example url>')
const message = `Here's the latest video: ${videoUrl}`
await sendMessageToChatId(message)
return new Response('OK')
} else if (text.startsWith('/<example>')) {
const post = await scrapePost('<example url>')
const message = `Here's the latest post: ${post.title}\n${post.url}`
await sendMessageToChatId(message)
return new Response('OK')
} else {
return new Response('Invalid command. Use the /help command to see available options.')
}
}
async function scrapeVideoUrl(url) {
const response = await fetch(url)
const html = await response.text()
const cheerio = require('cheerio')
const $ = cheerio.load(html)
const videoUrl = $('div.media > a').attr('href')
return videoUrl
}
async function scrapePost(url) {
const response = await fetch(url)
const html = await response.text()
const cheerio = require('cheerio')
const $ = cheerio.load(html)
const post = {
title: $('div.content h1').text(),
url: url
}
return post
}
async function sendMessageToChatId(message) {
const telegramApiUrl = "https://api.telegram.org/bot<token>/sendMessage";
const chatId = "<id>";
const response = await fetch(telegramApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: chatId,
text: message
})
})
}
There is zero response on the telegram side, even doe on web side everything seems to be fine.

Related

Puppeteer: How to bypass FUNCAPTCHA without submit button

I'm going to get right to the point. I'm trying to bypass Twitch's login funcaptcha using 2captcha's API. Everything works well: My bot communicates with 2captcha fast enough where the captcha won't timeout and my bot receives the token needed to authenticate the captcha and login, except there is no submit button to actually go through with the login. To the best of my knowledge, I've looked through every Github post, every stackoverflow post regarding this issue, and the best solution I could find was to look through the Google Network tab in the devtools to look for a function to call manually which would simulate a button and get you through the captcha. With my limited coding ability, I was able to find a function which references ArkoseEnforcement & the word "callback" which I believe is what I'm trying to find. After attempting to scavenge the sources tab and network tab the best I could find was this:
I've been trying to implement this function for an hour with no success and I also tried looking at "callback" and "ArkoseEnforment.funcaptcha_events" etc. etc.
I seriously have no idea how to implement them into my code and I would appreciate any help on where to start.
//require packages
require('dotenv').config(); const fs = require('fs'); const puppeteer = require('puppeteer'); const https = require('https');
//define varibles
var usernames = []; var pkValue; var surl = process.env.SURL ; var pk = process.env.PUBLICKEY ; var api = process.env.APIKEY;
const readFile = fs.readFileSync("accounts.txt").toString().split("\n");
//read accounts
console.log(`Reading ${readFile.length} lines.`);
for(i in readFile) {
(readFile[i].toLowerCase().startsWith("u") ? usernames.push(readFile[i].slice(10).replace("\r", "")) : null);
}
//get captcha
//retreive stream keys
async function getKey(username) {
const browser = await puppeteer.launch({headless:false}); const page = await browser.newPage(); const navigationPromise = page.waitForNavigation()
//get captcha
function getCaptcha(captchaID) {
https.get(`https://2captcha.com/res.php?key=${api}&action=get&id=${captchaID.slice(3)}`, (response) => {
var dataRes = '';
response.on('data', (chunk) => {
dataRes += chunk;
})
response.on('end', () => {
if (dataRes.toLowerCase()==="capcha_not_ready") {
setTimeout(() => {getCaptcha(captchaID)}, 5000)
}
else {
pkValue = dataRes.slice(3)
console.log(pkValue);
page.evaluate((pkValue) => {
//add token to val
document.querySelector('#FunCaptcha-Token').value = pkValue;
//submit form
//somehow need to submit the form here.
}, pkValue)
}
})
})
}
await page.goto(`https://dashboard.twitch.tv/u/${username}/settings/stream`, { waitUntil: ['networkidle2'] })
await page.setViewport({ width: 1920, height: 880 })
await page.waitForSelector('.sc-AxjAm #login-username')
await page.click('.sc-AxjAm #login-username')
await page.type('.sc-AxjAm #login-username', username)
await page.waitForSelector('.sc-AxjAm #password-input')
await page.click('.sc-AxjAm #password-input')
await page.type('.sc-AxjAm #password-input', process.env.PASSWORD)
await page.waitForSelector('.sc-AxjAm > .sc-AxjAm:nth-child(3) > .ScCoreButton-sc-1qn4ixc-0 > .ScCoreButtonLabel-lh1yxp-0 > .sc-AxjAm', {visible:true})
await page.click('.sc-AxjAm > .sc-AxjAm:nth-child(3) > .ScCoreButton-sc-1qn4ixc-0 > .ScCoreButtonLabel-lh1yxp-0 > .sc-AxjAm')
await page.waitForSelector('#FunCaptcha-Token')
//request 2captcha funcaptcha
await https.get(`https://2captcha.com/in.php?key=${api}&method=funcaptcha&publickey=${pk}&surl=${surl}&pageurl=https://dashboard.twitch.tv/u/${username}/settings/stream`, (response) => {
var data = '';
response.on('data', (chunk) => {
data += chunk;
})
response.on('end', () => {
setTimeout(() => {getCaptcha(data)}, 20000)
})
})
.on('error', (e) => {
console.log(e);
})
await page.waitForSelector('.sc-AxjAm:nth-child(2) > .sc-AxjAm > .ScCoreButton-sc-1qn4ixc-0 > .ScCoreButtonLabel-lh1yxp-0 > .sc-AxjAm', {visible:true,timeout:0})
var streamkey = await page.evaluate(() => document.querySelector('.sc-AxjAm:nth-child(2) > .sc-AxjAm > .ScCoreButton-sc-1qn4ixc-0 > .ScCoreButtonLabel-lh1yxp-0 > .sc-AxjAm').innerHTML);
await navigationPromise
await fs.appendFile('userkeys.txt', `${username}:${streamkey}`, e => console.log(`error: ${e}`))
}
console.log(`Getting keys.`);
(async () => {
for(i in usernames) {
await getKey(usernames[i]);
}
})();
//https://dashboard.twitch.tv/u/stokeshester/settings/stream trying to login as soon as I enter this link
Here is an example of my code logging the "tc-token" value for the funcaptcha:
Here is what the captcha interface looks like (no button):

Next JS API calls with auth0

I have a question about auth0 and next js.
For example, I have the next code (this code works)
//initialprops enables server-side rendering in a page and allows you to do initial data population
ModelsList.getInitialProps = async (ctx) => {
//this is static token to test from auth0.com
const accessToken = 'eyJhbG.....'
//fetching data
const res = await fetch('http://localhost:7071/api/bo/getModels', {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
const json = await res.json()
return { data: json }
}
As you can see, I have accessToken variable as a text. It's a problem for me
How can make accessToken dynamic?
Thanks a lot!
P.S please, dont reference to auth0 documentation, I have tried a lot. Provide, please, a real solution/example.
Ok, so this is what worked for me.
Let's say you've got api.example.com/resources. This where data actually is. You will need to proxy via next's api.
Inside your jsx component, you fetch next's api.
// components/Dashboard.jsx
const API_URL = "api/resources";
async function fetcher(url: any) {
const res = await fetch(url);
const json = await res.json();
return json;
}
function Dashboard() {
const { data, error } = useSWR(API_URL, fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>show your resources here</div>;
}
and now inside the next's api file you can fetch the actual endpoint you need.
// api/resources.js
import {
getAccessToken,
getSession,
withApiAuthRequired,
} from "#auth0/nextjs-auth0";
export default withApiAuthRequired(async function healthcheck(req, res) {
const session = await getSession(req, res);
const token = session?.idToken;
const response = await fetch("https://api.example.com/resources", {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
res.status(200).json(data);
});
if you get errors, check the jwts you're getting. Audience or scope mismatch errors are usually the main culprits.

Batch Geocode using Axios

Testing the HERE Batch GeoCode life-cycle through node application. We have similar working with Azure Mappings but they are crazy expensive.
Seems as if the initial post request is succeeding. But is stuck on "submitted" status during status check. And failing during result check with 404. Using axius to make the queries - with the documented examples.
const getStatus = async requestId => {
const url = statusURL(requestId);
const res = await axios.get(url);
const response = res.data.Response;
return response;
};
const getResult = async requestId => {
const url = resultURL(requestId);
const config = { headers: { 'Content-type': 'text/plain' } };
const res = await axios.get(url, config);
const response = res.data.Response;
return response;
};
const requestGeo = async input => {
const url = requestURL;
const res = await axios.post(url, input, {
headers: { 'Content-type': 'text/plain' },
});
const requestId = res.data.Response.MetaInfo.RequestId;
return requestId;
};
getStatus(requestId)
.then(res => {
console.log(res);
})
.catch(e => {
console.log(e);
});
const input = `recId|street|city|postalCode|country
1|425 Randolph St|Chicago||USA
2|31 St James Ave|Boston|02116|USA
3|Invalidenstrasse 117|Berlin|10115|DEU`;
requestGeo(input)
.then(console.log)
.catch(e => {
console.log(e);
});
If you don't specify the "&action=run" parameter in your initial request, then the job is being checked, stored and set as "submitted". This does not mean that it will be executed.
Alternatively you can send an "action=start"-request to start the job.
Having applied one of these two options, the job will be scheduled for execution and flagged as "accepted".

Properly fetching cached responses from workbox service worker

I was experimenting with workbox and service workers in general. I tried using NetworkFirst Strategy for my api calls. Console seems its working as expected but I could not display the cached response from service worker. Same is happening when using CacheFirst, response is not recieved by my dom render scripts. Am I missing something?
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');`
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
workbox.precaching.precacheAndRoute([]);
const cacheName = 'collection';
workbox.routing.registerRoute(
new RegExp('http://13.232.112.165/api/'),
workbox.strategies.networkFirst()
);
/*
const bgSyncPlugin = new workbox.backgroundSync.Plugin('post-req-queue', {
maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'PUT'
);
workbox.routing.registerRoute(
new RegExp("http://13.232.112.165/api/"),
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'DELETE'
);
*/
} else {
console.log(`Boo! Workbox didn't load 😬`);
}`
My Api call is as follows :
async function getAccounts() {
url = backend_uri+"accounts";
try{
var jsonResponse = await fetch(url, {headers: {
'Authorization' : "Token "+localStorage.getItem('user-token')
}});
const json = await jsonResponse.json();
const accounts = await json;
let renderString = "";
await accounts.forEach(element => {
renderString = renderString + `<div class='card'><div class='card-body'><strong>${element.name}</strong></div></div>`
});
containerElement.innerHTML += renderString;
}catch(e) {
console.log(e);
}
}
Should api calls in PWA made differently?
(I don't think your question is related to Workbox or PWAs; it appears to be more about using the Fetch API.)
There are some extra awaits and a few other issues that I see with your code; can you try the following?
async function getAccounts() {
const url = `${backend_uri}accounts`;
const response = await fetch(url, {
headers: {
'Authorization' : "Token "+localStorage.getItem('user-token')
},
});
const accounts = await response.json();
const divs = accounts.map(account => `<div class='card'>
<div class='card-body'>
<strong>${account.name}</strong>
</div>
</div>`);
containerElement.innerHTML += divs.join('');
}

fetch api not working after Network change - react native android

I have one application in which user can login and see some info.
Issue:
user able to login and see info and logout any number of times before changing network.but once user change network(from wifi to mobile or vice versa) and try to login and fetch information. it's throwing error:Network request failed at XMLHttpRequest.xhr.onerror (fetch.js:441)
Note: i am using fetch api for network call.
Fetch Api call:
export const request = async function request(path, body = null, method = 'GET') {
try {
const headers = {
'Content-Type': body instanceof FormData ? 'multipart/form-data' : 'application/json',
};
const token = await AsyncStorage.getItem('authToken');
if (token) {
headers.Authorization = token;
}
const config = {
method,
url: Config.API_URL + path,
headers,
};
if (!['HEAD', 'GET'].includes(method.toUpperCase())) {
config.body = body instanceof FormData ? body : JSON.stringify(body);
}
const response = await fetch(Config.API_URL + path, config);
const data = await response.json();
if (response.status >= 400) {
throw data.error;
}
return data;
} catch (e) {
console.log('Error', path, e);
return Promise.reject(e);
}
Error
Network request failed
at XMLHttpRequest.xhr.onerror (fetch.js:441)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:567)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:397)
at XMLHttpRequest.js:503
at RCTDeviceEventEmitter.emit (EventEmitter.js:179)
at MessageQueue.__callFunction (MessageQueue.js:351)
at MessageQueue.js:116
at MessageQueue.__guardSafe (MessageQueue.js:314)
SDK Version:
compileSdkVersion: 25
buildToolsVersion: "25.0.2"
minSdkVersion: 16
targetSdkVersion: 25
I am beginner in react native. not able to identify the problem. any help will be appreciate.
Thanks

Resources