So i have this python code that figures out channel chat id to send message for multiple channels in a given list.
I only have the channel invite link
I still didn't figure out how can i get the channel id by the name only.
import os
import telebot
API_KEY = os.environ['API_KEY']
bot = telebot.TeleBot(API_KEY)
a=input("edit msg.txt to send the msg if done press enter")
message=open("message.txt","a+")
bot.send_message(chat_id,message)
If you prefer to use Telegram API together with javascript and axios library then you might consider the following:
const method = 'get'
const headers: any = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
timestamp: +new Date(),
}
const options = { headers: { ...headers } }
const urlTelegramBase =
'https://api.telegram.org/bot123456:ABCDEF'
const urlGetUpdates = `${urlTelegramBase}/getUpdates`
const username = 'user_name'
const {
data: { result: messages },
} = await axios[method](urlGetUpdates, options)
const chat_id = messages.find(
messageBlock => messageBlock.message.chat.username === username
).message.chat.id
console.info('chat_id': chat_id)
You can use the getChat method to resolve a channel username to the chat id. You can also just send the message using the username - see the docs of sendMessage and e.g. this answer.
Related
I'm trying to get my head around the Nuxt /server API and can't seem to figure out how to send a POST request with form-data (ie files) to Nuxt server to forward on to an external service:
In my pages.vue file I have this method:
async function onSubmit() {
const formData = new FormData();
for (let file of form.files) {
await formData.append("image", file);
}
await $fetch("/api/send", {
method: "POST",
body: formData
});
}
and then in /server/api/send.js I have:
export default defineEventHandler(async (event) => {
const { method } = event.node.req;
// I THINK THE ISSUE IS HERE
const body =
method !== "GET" && method !== "HEAD"
? await readMultipartFormData(event)
: undefined;
const response = await $fetch.raw(https://*******, {
method,
baseURL: *********,
headers: {
},
body: body
});
return response._data;
}
I'm effectively creating a passthrough API using Nuxt so that the external endpoint isn't exposed to the end user. Just can't figure out how to access the formData in the correct format to pass through on the server side. I don't think I am supposed to use readMultipartFormData() because that seems to be parsing the data somehow whereas I just want to pass the formData straight through to the external API. Any tips?
I've tried using both readMultipartFormData() and readBody() and neither seem to work. I don't actually need to read the body but rather get it and pass it through without any formatting...
If you want to pass the data with formdata to the endpoint try this library:
https://www.npmjs.com/package/object-to-formdata
code:
import { serialize } from 'object-to-formdata';
const formData = serialize(body);
const response = await $fetch.raw(https://*******, {
method,
baseURL: *********,
headers: {
},
body: formData
});
I managed to make it work with ugly solution, first you have to update nuxt to version 3.2.0 min then here my front side
let jobApplicationDTO = {
firstName: values.firstName,
lastName: values.lastName,
email: values.email,
phoneNumber: values.phoneNumber,
company: values.company,
shortDescription: values.shortDescription
};
const formData = new FormData();
formData.append("application", new Blob([JSON.stringify(jobApplicationDTO)], {type: "application/json"}));
formData.append("file", values.file) ;
//formData.append("file", values.file );
await useFetch("/api/application", {
method: "POST",
body: formData,
onResponse({request, response, options}) {
// Process the response data
if (response.status === 200) {
errorMessage.value = "";
successMessage.value = "Your application wa sent successfully, you will be contacted soon !";
}
},
onResponseError({request, response, options}) {
console.debug(response);
if (response.status === 400) {
successMessage.value = "";
errorMessage.value = "There may be an issue with our server. Please try again later, or send an email to support#mantiq.com";
} else {
successMessage.value = "";
errorMessage.value = "Sorry we couldn’t send the message, there may be an issue with our server. Please try again later, or send an email to support#mantiq.com";
}
},
});
}
and server side
import {FormData} from "node-fetch-native";
export default defineEventHandler(async (event) => {
const {BACKEND_REST_API, ENQUIRY_TOKEN} = useRuntimeConfig();
//retrieve frontend post formData
const form = await readMultipartFormData(event);
const applicationUrl = BACKEND_REST_API + '/job/apply'
console.log("url used for enquiry rest call :" + applicationUrl);
console.log("Job application token :" + ENQUIRY_TOKEN);
const formData = new FormData();
console.log(form);
if (form) {
formData.append(form[0].name, new Blob([JSON.stringify(JSON.parse(form[0].data))], {type: form[0].type}));
formData.append(form[1].name, new Blob([form[1].data], {type: form[1].type}), form[1].filename);
}
console.log(formData.values);
return await $fetch(applicationUrl, {
method: "POST",
body: formData,
headers: {
Authorization: ENQUIRY_TOKEN,
},
});
})
What is funny is on frontend you have to create a formData , then to get content and to recreate a formData from your previous formData converted in MultiFormPart[], i created a ticket on nuxt to see how to do it properly
How can I validate title and message of MessaginPayload.
I have nodejs function to send notification message to my mobile app.
Sometime we got error, because message is exceed the limit.
Firebase mention that Notification messages can contain an optional data payload. Maximum payload for both message types is 4000 bytes, except when sending messages from the Firebase console, which enforces a 1024 character limit.
So how can I check the message payload in nodejs.
import * as firebaseAdmin from "firebase-admin";
import serviceAccount from "./service-account-file.json";
const admin = firebaseAdmin.initializeApp(
{
credential: firebaseAdmin.credential.cert(serviceAccount as
firebaseAdmin.ServiceAccount),
},
"server"
);
const fcm = admin.messaging();
const sendMessage = async (title: any, message: any) => {
var topic = "mydomain.org";
const payload: firebaseAdmin.messaging.MessagingPayload = {
notification: {
title: title,
body: message,
click_action: "FLUTTER_NOTIFICATION_CLICK", // required only for onResume or
onLaunch callbacks
},
};
return await fcm.sendToTopic(topic, payload);
};
export { sendMessage };
Creating subscription site in wix code. I keep getting a 400 unknown parameter: source error. (/subscripton)
if you can spot where i am going wrong it would be appreciated. thanks!
import { fetch } from 'wix-fetch';
export async function subscription(token, item) {
const cart = item;
const apiKey = "PRIVATEAPI";
const response = await
fetch("https://api.stripe.com/v1/subscriptions", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: encodeBody(token, cart)
});
if (response.status >= 200 && response.status < 300) {
const ret = await response.json();
return { "chargeId": ret.id };
}
let res = await response.json();
let err = res.error.message;
let code = res.error.code;
let type = res.error.type;
return { "error": err, "code": code, "type": type };
}
function encodeBody(token, cart) {
let encoded = "";
for (let [k, v] of Object.entries(cart)) {
encoded = encoded.concat(k, "=", encodeURI(v), "&");
}
encoded = encoded.concat("source=", encodeURI(token));
return encoded;
}
welcome to StackOverflow!
It looks like you're creating a Subscription. According to the API docs: https://stripe.com/docs/api/subscriptions/create?lang=ruby
customer is a required parameter when creating subscriptions on Stripe. You would need to create a Customer first, attaching a tokenized card to the Customer as a source. Then, you can create a subscription, by passing customer: customer.id
Also, is this request being made client-side? Requests made with your secret API key should be made from your server-side code and preferably using Stripe's API libraries: https://stripe.com/docs/libraries
Since you're using Subscriptions, you should also look into the new version of Stripe Checkout (https://stripe.com/docs/payments/checkout), it allows creating subscriptions with client-side code with just a few lines of code!
You're likely passing additional keys that you're not expecting to when you call encodeBody(token, cart).
You should verify that the keys you're passing in token and cart are all valid according to the documentation at https://stripe.com/docs/api/subscriptions/create.
I am new at mobile development and I choose React native, but I want to send remote push notification to a specific user. Can I use this library: react-native-push-notification ? there is a complete tutorial for that ?
Yes you can use this library https://github.com/evollu/react-native-fcm to connect your application with firebase, Then all you have to do is to log the device token that enable you to push notification for this device only with firebase
You have to save the UUID of each user and then you can use axios to send push notification to those users.
export const sendNotificationFirebaseAPI = async (
token: string,
title: string,
body: string,
data?: object,
) => {
if (token != '') {
const headers = {
Authorization: `key=${GOOGLE_FCM_KEY}`,
'Content-Type': 'application/json',
}
const bodyToSend = JSON.stringify({
to: token,
notification: {
title,
body,
},
data,
})
try {
await axios({
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: headers,
data: bodyToSend,
})
} catch (err) {
return { err }
}
}
}
I hope it helps you!
See google firebase documentation for more details: https://firebase.google.com/docs/cloud-messaging/http-server-ref
Check react-native-firebase.
Section: Cloud Messaging.
I would like to make a simple api GET request to get user email based on account name/username.
I am using axios and when I make GET request using this https://api.github.com/users/[username]
I get back everything I need(repository, followers...) except for the user email. It is always null. It would be enough for me to get just the email from users that set it as a public on their profile but no matter what it is set to it will always return null. I am reading that maybe I need authorisation. I made personal Access Token on my github account but how would I use it? What si the best way to get user email?
This is what I have now
import axios from 'axios'
const REQUEST = 'https://api.github.com/users/'
module.exports = {
getData: (accountName) => {
const encodedAccountName = encodeURIComponent(accountName)
const requestUrl = `${REQUEST}${encodedAccountName}`
return axios.get(requestUrl).then((res) => {
return res
})
}
}
Ok. I managed to get this working like this. I simply send a header with personalAccessToken together with request. You can get personal access token on github page under settings/Personal access token/Generate new token and choose user:email for scope. It would be good to use ENV variable now for access token.
import axios from 'axios'
const REQUEST = 'https://api.github.com/users/'
var config = {
headers: {'Authorization': 'token 847762643...'}
}
module.exports = {
getData: (accountName) => {
const encodedAccountName = encodeURIComponent(accountName)
const requestUrl = `${REQUEST}${encodedAccountName}`
return axios.get(requestUrl, config).then(res => {
return res
})
}
}
You can look at the Requestable.js object from GitHub.js tool
It does define the AuthorizationHeader based on a token:
this.__apiBase = apiBase || 'https://api.github.com';
this.__auth = {
token: auth.token,
username: auth.username,
password: auth.password
};
if (auth.token) {
this.__authorizationHeader = 'token ' + auth.token;
} else if (auth.username && auth.password) {
this.__authorizationHeader = 'Basic ' + Base64.encode(auth.username + ':' + auth.password);
}
I was able to get user email from GitHub API using below code.
https://api.github.com/user/emails?access_token=${token}