我制作了一个Discord机器人,希望在其中添加牛津字典API。
因此,如果您输入“!findword to search”,机器人将返回单词的含义
我已经做了几乎所有的事情,我有一个python脚本,它接受字符串输入并返回它的含义。 我有一个JS文件,它接受用户输入,然后做出相应的响应
我想做的是,在JS文件中获取用户输入,将其发送到python文件,该文件返回单词的含义
我正在使用Heroku
通过bot托管
我需要您的帮助,让我知道如何将输入字符串从bot.js
发送到trying.py
,然后将字符串数组从trying.py
返回到bot.js
两个文件的代码均为:
trying.py
import requests
import json
app_id = 'my-app-id'
app_key = 'my-app-key'
language = 'en-gb'
word_id = 'Hello'
fields = 'definitions'
strictMatch = 'false'
url = 'https://od-api.oxforddictionaries.com:443/api/v2/entries/' + language + '/' + word_id.lower() + '?fields=' + fields + '&strictMatch=' + strictMatch;
r = requests.get(url, headers = {'app_id': app_id, 'app_key': app_key})
theListOfMeanings = r.json()
if 'error' in theListOfMeanings:
print("Sorry, I couldn't find ",word_id," in the dictionary\nPlease check the spelling")
else:
counter=1
print("The different meanings of",word_id," are -")
for j in theListOfMeanings['results']:
for x in j['lexicalEntries']:
for i in (x['entries'][0]['senses']):
print(counter,". "," ".join(i['definitions']))
counter+=1
Bot.js
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json') //TEMPORARY
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('guildMemberAdd', member => {
member.guild.channels.get('channelID').send("Welcome");
});
client.on('message', msg => {
theMessage = msg.content
if (msg.content === '!hello') {
msg.reply('Hii ! :grin:');
}
else if (theMessage.slice(0, 5) === '!find'){
msg.reply('Hi, my name is Norm :neutral_face:')
//theMessage.pop(0)
theMessage = theMessage.substring(5);
msg.reply(theMessage);
}
});
client.login(auth.token);
我同意用JS重新编写python脚本是个好主意。 但是,问题是,Oxford上可用的node.js代码返回一个输出,我不知道如何管理。 上面的链接中提供了node.js代码(替换为trying.py),它的输出如下:
如果有人能告诉我如何使用返回的JS代码,我将非常感激
OXFORD API代码(Node.js(trying.py的替代品))
const http = require("https");
const app_id = "my_app_id"; // insert your APP Id
const app_key = "my_app_key"; // insert your APP Key
const wordId = "ace";
const fields = "pronunciations";
const strictMatch = "false";
const options = {
host: 'od-api.oxforddictionaries.com',
port: '443',
path: '/api/v2/entries/en-gb/' + wordId + '?fields=' + fields + '&strictMatch=' + strictMatch,
method: "GET",
headers: {
'app_id': app_id,
'app_key': app_key
}
};
http.get(options, (resp) => {
let body = '';
resp.on('data', (d) => {
body += d;
});
resp.on('end', () => {
let parsed = JSON.stringify(body);
console.log(parsed);
});
});
通过使用
node-fetch
npm模块在JS中重新编码程序,在注释中解决了问题有两种方法你可以去,但我会建议你只烧瓶,因为我相信这将需要你的努力最小的开始
您需要创建Flask应用程序,将javascript代码作为与Flask视图对话的静态资产。flask视图在内部执行您在python脚本中编写的逻辑,并向javascript代码返回json响应,以Flask quickstart和Flask by Example – Project Setup作为起点
当您在本地计算机上完成应用程序时,这里是deploying python application on Heroku和Deploy Python Flask App on Heroku 上的指南
下面是一个工作的Javascript代码段,它使用节点获取为您获取定义
输出
相关问题 更多 >
编程相关推荐