TypeError: Cannot read properties of undefined (reading 'length') MYSQL Issue Js - mysql

Every time I do a command on my bot that has to do with MySQL an error occurs, and my bot shut down
module.exports.run = async (bot, message, con, log, role, makeid, args) => {
con.query(`SELECT discord_id,Blacklisted,Reason FROM whitelistbot WHERE discord_id = '${message.author.id}'`, function (err, results, fields) {
if(results.length) {
if(results[0].Blacklisted === "True") {
let blacklisted = results[0].Blacklisted
let reason = results[0].Reason
const embedn = new discord.MessageEmbed()
.setColor('#0099ff')
.setDescription('**Bot Whitelist**')
.addField('Info Buyer','```md\n#Blacklist = '+blacklisted+'\n#Reason = '+reason+'\n```', true)
.setTimestamp()
message.author.send(embedn).catch(error => {
const embed2 = new discord.MessageEmbed()
.setColor('#0099ff')
.setDescription('**Bot Whitelist**')
.addField('Send Message Fail','```\nI cannot message you, open your messages!\n```', true)
.setTimestamp()
message.channel.send(embed2)
})
Hoping someone can help me solve this issue thank you in advance!

Related

Error: Expected a value of type 'String', but got one of type '_MapStream<dynamic, Iterable<Post>>'

I have wrote the following code on server.
server code:
import 'dart:convert';
import 'package:mongo_dart/mongo_dart.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class PostsSocketApi {
PostsSocketApi(this.store);
final List<WebSocketChannel> _sockets = [];
final DbCollection store;
Handler get router {
return webSocketHandler((WebSocketChannel socket) {
socket.stream.listen((message) async {
final data = json.decode(message);
print(data);
if (data['action'] == 'LOGIN') {
final user = await store.findOne(
where.eq('name', data['name']).eq('password', data['password']));
if (user != null) {
for (final ws in _sockets) {
ws.sink.add(json.encode('name'));
// probably there must be .toString() ^^^
}
}
if (user == null) {
for (final ws in _sockets) {
ws.sink.addError('NOSUCHUSER');
}
}
}
});
_sockets.add(socket);
});
}
}
And now I want to get the 'name' field into my variable tmp_name to compare it with name on login field, like that:
login code:
void loginUser() async {
final name = emailController.text;
final password = passwordController.text;
widget.api.send(
json.encode({'action': 'LOGIN', 'name': name, 'password': password}));
String tmp_name = widget.api.getName;
// method from API ^^^^^^^
if (tmp_name == name) {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString('name', name);
});
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) => Home()));
} else {
print('error: no such user');
}
}
API code in App:
class PostsSocketApi {
PostsSocketApi()
: _api = WebSocketChannel.connect(
Uri.parse('ws://localhost:8082/posts-ws/'));
final WebSocketChannel _api;
Stream<List<Post>> get stream => _api.stream.map<List<Post>>((data) {
final decoded = json.decode(data);
return (decoded as List)
.map<Post>(
(json) => Post.fromJson(json),
)
.toList();
});
ValueChanged<String> get send => _api.sink.add;
get getName => _api.stream.map((data) {
final decoded = json.decode(data['name']);
return (decoded as List).map<Post>(
(json) => Post.fromJson(json),
);
});
}
However, I got the following error in APP code and don't know how to solve it.
Error: Expected a value of type 'String', but got one of type '_MapStream<dynamic, Iterable<Post>>'
Server code works fine (compare data and print if it's wrong user)
Server response on register:
{action: ADDUSER, name: 6, password: 6, id: 6}
Server response on login as existing user:
{action: LOGIN, name: 6, password: 6}
Server response on login as NOT-existing user:
{action: LOGIN, name: fqfqfq, password: qfqfqfq}
NOSUCHUSER
ERROR - 2022-03-21 11:55:27.183011
Asynchronous error
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
PostsSocketApi.router.<fn>.<fn>
package:io/api/socket_api.dart:79
For Ruchit:
userID type is String. If I write like that, the same error thrown.
get getName => _api.stream.map((data) {
final decoded = json.decode(data['name']);
return (decoded as List)
.map<String>((json) => Post.fromJson(json).userID);
});
But, if I write like that, I get the type error:
error: The return type 'String' isn't a 'Post', as required by the closure's context.
Code:
get getName => _api.stream.map((data) {
final decoded = json.decode(data['name']);
return (decoded as List)
.map<Post>((json) => Post.fromJson(json).userID );
});
Any ideas? (Even about refactoring other code)
I'm tried to find some explanations in documentation, but... Write if u need some more code or explanations. Or if you can give me advice about how to make login by another way - tell me.
Please help me if you can <3
Here you are returning whole post object and you are getting as String which mismatches thus it is showing error.
get getName => _api.stream.map((data) {
final decoded = json.decode(data['name']);
return (decoded as List).map<Post>(
(json) => Post.fromJson(json).field, //here field is the field you want from Post object and you are getting string so this field should have type string.
//eg. Post.fromJson(json).name
);
});

i want to split a result in mysql can you help me?

Well, first that's my code here
client.on('message', async (message) => { //فايف ام داتابيس
if(message.channel.type == 'dm') return;
var prefix = prefixx.get(message.guild.id);
if(message.author.bot) return;
if(message.content.toLowerCase().startsWith(prefix + 'ip')) {
if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('ما عندك رتبة عشان تستخدم الأمر هذا');
let args = message.content.split(" ");
connection1.query(
`select ifnull((select last_login from vrp_users where id = ${args[1]}),'لا يوجد ايدي بهذا الرقم') As ResultFound`, function (error, result, fields) {
if (error) throw error;
console.log(`Got IP of user ${args[1]}`);
if(!result) return message.channel.send('There is an error');
if(error) return message.channel.send('There is an error');
let embed = new Discord.MessageEmbed() .setColor('RANDOM') .setTitle(`اي بي ${args[1]}`) .setThumbnail(message.guild.iconURL( { dynamic : true } )) .setAuthor(client.user.tag, client.user.avatarURL( {dynamic : true} )) .addField('IP', `\`${result[0].ResultFound}\``);
message.channel.send(embed)
}
);
}
});
the result comes like this :
77.223.232.147 23:50:55 29/06/2020
i want the result be only the ip can you guys help me?
Try this:
.addField('IP', `\`${result[0].ResultFound.split(' ')[0]}\``);
For example, if the result is what you provided in your question:
const result = '77.223.232.147 23:50:55 29/06/2020'
// split the message by every space
const array = result.split(' ');
console.log(array[0]); // IP adress
console.log(array[1]); // time (I presume)
console.log(array[2]); // date

Discord.js V12 Vote command not working somehow

so I am working on a command that makes like a vote embed, and it doesn't really work. when I use (in my case) $repvote #user it doesn't recognize the user or anything.., let me know for any solutions!
if (message.author.bot) return;
if (message.content.startsWith(prefix + "repvote")) {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send('You do not have that permission! :x:').then(message.react('❌'));
let repUser = message.mentions.members.first()
if(!repUser) return message.channel.send("Please mention the user you want to setup the vote for!").then(message.react('❌')).then(msg => { msg.delete({ timeout: 5000 });
const repVoteEmbed = new Discord.MessageEmbed()
repVoteEmbed.setTitle("Vote for Representative Members :crown:")
repVoteEmbed.setDescription(`User ${repUser} wants to recieve Representative Members :crown: role! Do you agree?`)
repVoteEmbed.setFooter(`Vote by: ${message.author.tag}, started on : ${message.createdAt}`)
message.channel.send({repVoteEmbed}).then(message.react('✔')).then(message.react('❌'))
})
}})```
You missing message.channel.send(embed).then(msg =>....
Message channel send return a promise of the sent message, so you need use it to react
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.content.startsWith(prefix + 'repvote')) {
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react('❌'));
let repUser = message.mentions.members.first();
if (!repUser) {
message.channel.send('Please mention the user you want to setup the vote for!').then((declineMsg) => {
message.react('❌');
declineMsg.delete({
timeout: 5000,
});
});
return;
}
const repVoteEmbed = new Discord.MessageEmbed();
repVoteEmbed.setTitle('Vote for Representative Members :crown:');
repVoteEmbed.setDescription(`User ${repUser} wants to recieve Representative Members :crown: role! Do you agree?`);
repVoteEmbed.setFooter(`Vote by: ${message.author.tag}, started on : ${message.createdAt}`);
message.channel.send(repVoteEmbed).then((msg) => {
msg.react(`✔`).then(() => msg.react('❌'));
});
}
});

Why the current time in node js and when i try to input in mysql is different?

I just confuse with this case. I've been try to make sure the time zone in MySql and see the data that out from Date(Date.now()). That's all is correct with my timezone. But when i try to input the data to MySql, and i check in my Database. The time zone is wrong and different with my Time zone. Is there anyone can help me ?
This my code
const Employee = require('../models/employee');
const History = require('../models/history');
async createHistory(employee){
let result;
try {
const checkData = await Employee.findOne({where :
{employeeId : employee.employeeId}
});
if(checkData !== null){
const createData = await History.create({
employeeId : employee.employeeId,
in : Date(Date.now())
});
console.log(date.toLocaleString());
console.log('True')
}else {
result = {message : false}
}
} catch (e) {
logEvent.emit('APP_ERROR',{
logTitle: '[CREATE-HISTORY-ERROR]',
logMessage: e
});
}
return result;
}
The Time in field 'in' is wrong, it should be 14:43
I just get the answer,
The answer is .. because i using Sequelize to store the data to MySql i have to input the time zone in my connection.
Here my code :
const connection = new Sequelize(
{
timezone: "+07:00"
}
);

No response when transaction is submitted to sawtooth intkey TP

I am trying to set up a transaction processor with hyperledger sawtooth. I tested my TP with sawtooth 1.0 and it worked fine. But when I used sawtooth 1.1 network, my transactions are not processed. It seems like the request does not reach the TP. I then tried the intkey TP from the sdk and that also has the same problem. I matched the transaction submit process from the documentation but for no good.
Sawtooth network docker file
version: "2.1"
services:
settings-tp:
image: hyperledger/sawtooth-settings-tp:1.1
container_name: sawtooth-settings-tp-default
depends_on:
- validator
entrypoint: settings-tp -vv -C tcp://validator:4004
validator:
image: hyperledger/sawtooth-validator:1.1
container_name: sawtooth-validator-default
expose:
- 4004
ports:
- "4004:4004"
# start the validator with an empty genesis batch
entrypoint: "bash -c \"\
sawadm keygen && \
sawtooth keygen my_key && \
sawset genesis -k /root/.sawtooth/keys/my_key.priv && \
sawadm genesis config-genesis.batch && \
sawtooth-validator -vv \
--endpoint tcp://validator:8800 \
--bind component:tcp://eth0:4004 \
--bind network:tcp://eth0:8800 \
\""
rest-api:
image: hyperledger/sawtooth-rest-api:1.1
container_name: sawtooth-rest-api-default
ports:
- "8008:8008"
depends_on:
- validator
entrypoint: sawtooth-rest-api -C tcp://validator:4004 --bind rest-api:8008
Transaction processor
/**
* Copyright 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ------------------------------------------------------------------------------
*/
'use strict'
const { TransactionHandler } = require('sawtooth-sdk/processor/handler')
const {
InvalidTransaction,
InternalError
} = require('sawtooth-sdk/processor/exceptions')
const crypto = require('crypto')
const cbor = require('cbor')
// Constants defined in intkey specification
const MIN_VALUE = 0
const MAX_VALUE = 4294967295
const MAX_NAME_LENGTH = 20
const _hash = (x) =>
crypto.createHash('sha512').update(x).digest('hex').toLowerCase()
const INT_KEY_FAMILY = 'intkey'
const INT_KEY_NAMESPACE = _hash(INT_KEY_FAMILY).substring(0, 6)
const _decodeCbor = (buffer) =>
new Promise((resolve, reject) =>
cbor.decodeFirst(buffer, (err, obj) => (err ? reject(err) : resolve(obj)))
)
const _toInternalError = (err) => {
let message = (err.message) ? err.message : err
throw new InternalError(message)
}
const _setEntry = (context, address, stateValue) => {
let entries = {
[address]: cbor.encode(stateValue)
}
return context.setState(entries)
}
const _applySet = (context, address, name, value) => (possibleAddressValues) => {
let stateValueRep = possibleAddressValues[address]
let stateValue
if (stateValueRep && stateValueRep.length > 0) {
stateValue = cbor.decodeFirstSync(stateValueRep)
let stateName = stateValue[name]
if (stateName) {
throw new InvalidTransaction(
`Verb is "set" but Name already in state, Name: ${name} Value: ${stateName}`
)
}
}
// 'set' passes checks so store it in the state
if (!stateValue) {
stateValue = {}
}
stateValue[name] = value
return _setEntry(context, address, stateValue)
}
const _applyOperator = (verb, op) => (context, address, name, value) => (possibleAddressValues) => {
let stateValueRep = possibleAddressValues[address]
if (!stateValueRep || stateValueRep.length === 0) {
throw new InvalidTransaction(`Verb is ${verb} but Name is not in state`)
}
let stateValue = cbor.decodeFirstSync(stateValueRep)
if (stateValue[name] === null || stateValue[name] === undefined) {
throw new InvalidTransaction(`Verb is ${verb} but Name is not in state`)
}
const result = op(stateValue[name], value)
if (result < MIN_VALUE) {
throw new InvalidTransaction(
`Verb is ${verb}, but result would be less than ${MIN_VALUE}`
)
}
if (result > MAX_VALUE) {
throw new InvalidTransaction(
`Verb is ${verb}, but result would be greater than ${MAX_VALUE}`
)
}
// Increment the value in state by value
// stateValue[name] = op(stateValue[name], value)
stateValue[name] = result
return _setEntry(context, address, stateValue)
}
const _applyInc = _applyOperator('inc', (x, y) => x + y)
const _applyDec = _applyOperator('dec', (x, y) => x - y)
class IntegerKeyHandler extends TransactionHandler {
constructor () {
super(INT_KEY_FAMILY, ['1.0'], [INT_KEY_NAMESPACE])
}
apply (transactionProcessRequest, context) {
return _decodeCbor(transactionProcessRequest.payload)
.catch(_toInternalError)
.then((update) => {
//
// Validate the update
let name = update.Name
if (!name) {
throw new InvalidTransaction('Name is required')
}
if (name.length > MAX_NAME_LENGTH) {
throw new InvalidTransaction(
`Name must be a string of no more than ${MAX_NAME_LENGTH} characters`
)
}
let verb = update.Verb
if (!verb) {
throw new InvalidTransaction('Verb is required')
}
let value = update.Value
if (value === null || value === undefined) {
throw new InvalidTransaction('Value is required')
}
let parsed = parseInt(value)
if (parsed !== value || parsed < MIN_VALUE || parsed > MAX_VALUE) {
throw new InvalidTransaction(
`Value must be an integer ` +
`no less than ${MIN_VALUE} and ` +
`no greater than ${MAX_VALUE}`)
}
value = parsed
// Determine the action to apply based on the verb
let actionFn
if (verb === 'set') {
actionFn = _applySet
} else if (verb === 'dec') {
actionFn = _applyDec
} else if (verb === 'inc') {
actionFn = _applyInc
} else {
throw new InvalidTransaction(`Verb must be set, inc, dec not ${verb}`)
}
let address = INT_KEY_NAMESPACE + _hash(name).slice(-64)
// Get the current state, for the key's address:
let getPromise = context.getState([address])
// Apply the action to the promise's result:
let actionPromise = getPromise.then(
actionFn(context, address, name, value)
)
// Validate that the action promise results in the correctly set address:
return actionPromise.then(addresses => {
if (addresses.length === 0) {
throw new InternalError('State Error!')
}
console.log(`Verb: ${verb} Name: ${name} Value: ${value}`)
})
})
}
}
module.exports = IntegerKeyHandler
SendTransaction
const {createContext, CryptoFactory} = require('sawtooth-sdk/signing')
const cbor = require('cbor')
const {createHash} = require('crypto')
const {protobuf} = require('sawtooth-sdk')
const crypto = require('crypto')
// Creating a Private Key and Signer
const context = createContext('secp256k1')
const privateKey = context.newRandomPrivateKey()
const signer = new CryptoFactory(context).newSigner(privateKey)
const _hash = (x) => crypto.createHash('sha512').update(x).digest('hex').toLowerCase()
// Encoding Your Payload
const payload = {
Verb: 'get',
Name: 'foo',
Value: null
}
const payloadBytes = cbor.encode(payload)
let familyAddr = _hash('intkey').substring(0, 6);
let nameAddr = _hash(payload.Name).slice(-64);
let addr = familyAddr + nameAddr;
console.log(addr);
// Create the Transaction Header
const transactionHeaderBytes = protobuf.TransactionHeader.encode({
familyName: 'intkey',
familyVersion: '1.0',
inputs: [addr],
outputs: [addr],
signerPublicKey: signer.getPublicKey().asHex(),
batcherPublicKey: signer.getPublicKey().asHex(),
dependencies: [],
payloadSha512: createHash('sha512').update(payloadBytes).digest('hex')
}).finish()
// Create the Transaction
const signature = signer.sign(transactionHeaderBytes)
const transaction = protobuf.Transaction.create({
header: transactionHeaderBytes,
headerSignature: signature,
payload: payloadBytes
})
// Create the BatchHeader
const transactions = [transaction]
const batchHeaderBytes = protobuf.BatchHeader.encode({
signerPublicKey: signer.getPublicKey().asHex(),
transactionIds: transactions.map((txn) => txn.headerSignature),
}).finish()
// Create the Batch
const headerSignature = signer.sign(batchHeaderBytes)
const batch = protobuf.Batch.create({
header: batchHeaderBytes,
headerSignature: headerSignature,
transactions: transactions
})
// Encode the Batch(es) in a BatchList
const batchListBytes = protobuf.BatchList.encode({
batches: [batch]
}).finish()
// Submitting Batches to the Validator
const request = require('request')
request.post({
url: 'http://localhost:8008/batches',
body: batchListBytes,
headers: {'Content-Type': 'application/octet-stream'}
}, (err, response) => {
if (err) return console.log(err)
console.log(response.body)
})
There are architectural differences in the Hyperledger Sawtooth when moving from 1.0 to 1.1. One major difference is that the consensus engine is moved outside the validator service. In your docker-compose file, there is no consensus engine component also the validator service is not listening on a port for the consensus engine.
The consensus engine drives the block creation. For example, a timer expiry event in the PoET will cause the validator to create a block, validate, broadcast to other members in the network. Also, a confirmation from the consensus engine will make the validator service to commit the block to the blockchain.
Please find an example docker-compose file with the PoET consensus engine here https://github.com/hyperledger/sawtooth-core/blob/1-1/docker/compose/sawtooth-default-poet.yaml . Additionally you may try out https://github.com/hyperledger/sawtooth-core/blob/1-1/docker/compose/sawtooth-default.yaml for local dev test.
There is an explanation in the Hyperledger Sawtooth FAQ for upgrading from 1.0 version to the version 1.1 https://sawtooth.hyperledger.org/faq/upgrade/#id1 . Please feel free to ask more questions or suggestions to update these documentation.
You can also refer to the official documentation to learn in detail for different versions here https://sawtooth.hyperledger.org/docs/.