How can I detect the distance between 2 entities, in mineflayer? - javascript

I am trying to make the bot attack everything it sees, but it gets kicked for trying to hit something out of it's range, here is my code
var settings = {
username: 'testingbot',
host: 'localhost',
port: 25565,
};
const bot = mineflayer.createBot(settings);
var killer_mode = true;
bot.on("move", () => {
let friend = bot.nearestEntity();
if (friend) {
bot.lookAt(friend.position.offset(0, friend.height, 0));
bot.setControlState('sprint', killer_mode)
bot.setControlState('forward', killer_mode)
}
if (killer_mode) {
bot.attack(friend)
}
});
i tried adding if friend into if (killer_mode), idk what i thought that would make it do

Related

reply from group chat (telegram bot - support) (NODE JS)

help please, I am writing a telegram bot for feedback, at the moment it works in a private chat (i.e. the user writes to the bot - I answer reply the bot via reply and the user receives SMS from the bot), but does not work in the group chat( in a group I can see the user's messages, but I can't reply to the user through reply). it is necessary that any user from the group can reply to the user's message
const bot = new Telegraf(token, {});
let replyText = {
'helloAdmin': '...',
'helloUser': '...',
'replyWrong': '....'
};
let isAdmin = userId => {
return userId === admin;
};
let forwardToAdmin = ctx => {
if (isAdmin(ctx.message.from.id)) {
ctx.reply(replyText.replyWrong);
} else {
ctx.forwardMessage(admin, ctx.from.id, ctx.message.id);
}
};
bot.start(ctx => {
ctx.reply(isAdmin(ctx.message.from.id)
? replyText.helloAdmin
: replyText.helloUser);
});
bot.on('message', ctx => {
if (ctx.message.reply_to_message && ctx.message.reply_to_message.forward_from && isAdmin(ctx.message.from.id)) {
ctx.telegram.sendCopy(ctx.message.reply_to_message.forward_from.id, ctx.message);
} else {
forwardToAdmin(ctx);
}
});
bot.launch();
there is a getChatAdministrators method (https://core.telegram.org/bots/api#getchatadministrators), I guess you can use it to get Admins of the group and check if one of them is replied. In that case forward it back to user

Antispam for telegram bot

I am working on creating a telegram bot, I want to make an anti-spam system, that is, when a person presses a button too many times, the bot will freeze for him for a certain number of seconds, it is possible to write a message about blocking. I just started learning JavaScript.
I use node-telegram-bot-api.
import {
bot
} from '../token.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
return bot.sendMessage(chatId, 'error');
});
}
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use: You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}

Simple MSAL Login/Authentication in JavaScript

I'm trying to do a simple login to Azure AD using the MSAL for JavaScript v2.0 library. We want users to be able to authenticate into our site with their work Microsoft accounts. All I need to do is be able to authenticate/login the user via Microsoft, and if they can login via their work Microsoft account, then they're granted access to our site.
I'm using the Javascript library and have followed the code from the Github page and while the login prompt is coming up, afterwards I have no idea how to check if the user is signed in.
Here's the code I'm using, which is basically what's in the sample code from Github:
<script type="text/javascript" src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js"></script>
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "[ClientID goes here]",
authority: "https://login.microsoftonline.com/[tenant ID]",
knownAuthorities: ["login.microsoftonline.com"],
protocolMode: "OIDC",
redirectUri: "[page on our site that doesn't have MSAL auth, listed in Azure Reply URLs]"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: true, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["User.Read"]
};
const silentRequest = {
scopes: ["openid", "profile", "User.Read"]
};
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;
let signInType;
let accountId = "";
let credType = "";
// Create the main myMSALObj instance
const myMSALObj = new msal.PublicClientApplication(msalConfig);
// Register Callbacks for Redirect flow
myMSALObj.handleRedirectPromise().then(handleResponse).catch((error) => {
console.log(error);
});
function handleResponse(resp) {
alert("beginning handleResponse");
if (resp !== null) {
accountId = resp.account.homeAccountId;
credType = resp.account.credentialType;
myMSALObj.setActiveAccount(resp.account);
alert("response not null (already auth), accountId: " + accountId + ", credType: " + credType);
}
else {
const currentAccounts = myMSALObj.getAllAccounts();
if (!currentAccounts || currentAccounts.length < 1) {
alert("currentAccounts null/empty, going to signIn");
signIn("loginRedirect");
//return;
}
else if (currentAccounts.length > 1) {
// add choose account code here
alert("currentAccounts has multiple");
}
else if (currentAccounts.length === 1) {
const activeAccount = currentAccounts[0];
myMSALObj.setActiveAccount(activeAccount);
accountId = activeAccount.homeAccountId;
credType = activeAccount.credentialType;
alert("currentAccounts == 1; accountId: " + accountId + ", credType: " + credType);
}
}
}
async function signIn(method) {
signInType = isIE ? "loginRedirect" : method;
if (signInType === "loginPopup") {
return myMSALObj.loginPopup(loginRequest).then(handleResponse).catch(function (error) {
console.log(error);
});
}
else if (signInType === "loginRedirect") {
return myMSALObj.loginRedirect(loginRequest);
}
}
function signOut() {
const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId)
};
myMSALObj.logoutRedirect(logoutRequest);
}
async function getTokenPopup(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
console.log("acquiring token using popup");
return myMSALObj.acquireTokenPopup(request).catch(error => {
console.error(error);
});
}
else {
console.error(error);
}
});
}
// This function can be removed if you do not need to support IE
async function getTokenRedirect(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
console.log("acquiring token using redirect");
myMSALObj.acquireTokenRedirect(request);
}
else {
console.error(error);
}
});
}
So what happens upon going to this page is I get the two alerts saying "beginning handleResponse" and then "currentAccounts null/empty, going to signIn."
Then I'm redirected to MS sign-in page which I do with my work MS account. This succeeds.
I'm then redirected to the site I have listed in Azure Reply URLs, another page on our site that isn't secure and has no Azure login code.
The problem is I have no idea where to check that the user is signed in. If I try and check immediately after the signIn("loginRedirect") call in the handleResponse() function on the first page, the code never gets hit apparently. If I try and check on the page I'm redirected to, by instantiating the MSAL object and calling getAllAccounts(), this returns null.
It seems maybe on the page I'm redirected to I could call the ssoSilent() function (seems like this can check if user is authenicated?), but this requires a username/AccountId parameter. Well I don't frickin know this if a user hasn't (possibly) been authenticated yet! I don't really understand that.
So I don't know. It's probably something stupid I'm doing but I'm a pretty basic JavaScript person and am pretty much a total noob with authenication stuff. Any help would be epic.

Move voice chat users using Discord bot

I am trying to program a bot that, following a command, moves a user to a room a number of times of your choice.
For configuration and hosting I am using autocode.com, both "userId" and "number" are set correctly.
However, the user is not moved away.
This is the code
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
let isAdmin = (context.params.event.member.permissions & (1<<3)) === (1<<3);
if (isAdmin) {
let userId = context.params.event.data.options[0].value;
let number = context.params.event.data.options[1].value;
let result = await lib.discord.channels['#0.1.0'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `It's time to Jump for ` +number+ ' times'
});
for(let i = 0; i < number; i++){
await guild.member(userId).voice.setChannel("789946095341535242");
await sleep(1000)}
} else {
await lib.discord.channels['#0.1.0'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `This command is admin only!`,
});
}
I think the problem is at
await guild.member (userId) .voice.setChannel ("789946095341535242");
but I can't solve the problem, does anyone know what the problem could be and how to fix it?

Limit number of requests per minute using Supertest

We're using supertest with Typescript to test out APIs.
For some of them (e.g. user registration, change password, etc) an email address is sent that is required for confirmation (user confirm token, reset password token, etc).
In order to achieve this, we decided to use GuerillaMail, as it's a simple disposable email client with API. After doing the prerequisites (setting the email using their email), the following piece of code does its job in a couple of cases:
private async getEmailId(sid_token: string, emailType: EmailType): Promise<string> {
var mail;
var mailToken = this.getSidToken(sid_token);
//Keep trying until the email gets in the inbox
// Infinite loop is prevented by the jest framework timeout
while (!mail) {
const result = await request(this.guerillaMailApiUrl)
.get('')
.query({
f: 'check_email',
seq: 0,
sid_token: mailToken
});
if (result.body.list != undefined) {
mail = result.body.list.filter(m => m.mail_subject == emailType && m.mail_from == 'email#domain.com' && m.mail_read == 0)[0];
}
else {
mail = undefined;
}
}
return mail.mail_id;
}
However, it comes with a limitation of 20 requests per minute, limitation that is causing tests to fail.
Is there a way to limit the number of request made?
LATER EDIT:
I made it work by creating a delay:
async delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
and calling it right before exiting the while loop:
await this.delay(5000);
Is there a cleaner/nicer/efficient/performant/etc way of achieving this?
This one rate limiter that I used in my past projects Bottleneck https://www.npmjs.com/package/bottleneck
const limiter = new Bottleneck({
maxConcurrent: 20,
minTime: 60000
});
while (!mail) {
// set limiter here
const result = await limiter.schedule(() => request(this.guerillaMailApiUrl)
.get('')
.query({
f: 'check_email',
seq: 0,
sid_token: mailToken
}));
if (result.body.list != undefined) {
mail = result.body.list.filter(m => m.mail_subject == emailType && m.mail_from == 'email#domain.com' && m.mail_read == 0)[0];
} else {
mail = undefined;
}
}
Hope it helps

Categories