Javascript 如何在JS和Python之间通信?

Javascript 如何在JS和Python之间通信?,javascript,python,discord,Javascript,Python,Discord,我制作了一个Discord机器人,希望在其中添加牛津字典API。 因此,如果您输入“!查找要搜索的单词”,机器人将返回单词的含义 我已经做了几乎所有的事情,我有一个python脚本,它接受字符串输入并返回它的含义。 我有一个JS文件,它接受用户输入,然后做出相应的响应 我想做的是,在JS文件中获取用户输入,将其发送到python文件,该文件返回单词的含义 我正在使用Heroku通过bot托管 我需要您的帮助,让我知道如何将输入字符串从bot.js发送到trying.py,然后将字符串数组从try

我制作了一个Discord机器人,希望在其中添加牛津字典API。
因此,如果您输入“!查找要搜索的单词”,机器人将返回单词的含义

我已经做了几乎所有的事情,我有一个python脚本,它接受字符串输入并返回它的含义。 我有一个JS文件,它接受用户输入,然后做出相应的响应

我想做的是,在JS文件中获取用户输入,将其发送到python文件,该文件返回单词的含义

我正在使用Heroku通过bot托管

我需要您的帮助,让我知道如何将输入字符串从
bot.js
发送到
trying.py
,然后将字符串数组从
trying.py
返回到
bot.js

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
两个文件的代码均为:

正在尝试.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脚本是个好主意。 但是,问题是,在的node.js代码返回一个输出,我不知道如何管理。 上面的链接中提供了node.js代码(替换为trying.py),它的输出如下:

如果有人能告诉我如何使用返回的JS代码,我将非常感激

OXFORD API代码(Node.js(trying.py的替代品))


有两种方法你可以去,但我会建议你只烧瓶,因为我相信这将需要你的努力最小的开始

您需要创建Flask应用程序,将javascript代码作为与Flask视图对话的静态资产。flask视图在内部执行您在python脚本中编写的逻辑,并将json响应返回到javascript代码,查看并作为您的起点


当您在本地计算机上完成应用程序时,这里是指南和。

注释中的问题已通过使用
节点获取
npm模块在JS中重新编码程序解决。

要回答您的初始问题,下面是如何让两者通信。这假设JavaScript脚本和Python脚本都位于同一台机器上,并且可以通过stdin/stdout通道进行通信

#script.py
导入系统
word=sys.stdin.read().strip()
打印('的定义+单词)
//script.js
const{spawn}=require('child_进程');
//假设script.py位于同一文件夹中
constpython=spawn('python',['script.py']);
python.stdout.on('data',data=>{
常量定义=data.toString().trim();
console.log(定义);
});
constuserinput='Foo';
python.stdin.end(userInput);
运行时:

node script.js
它将打印:

Foo的定义
这里是一个工作的Javascript代码段,它使用节点获取为您获取定义

输出

hello
1. [interjection] used as a greeting or to begin a phone conversation
1. [noun] an utterance of ‘hello’; a greeting
1. [verb] say or shout ‘hello’
world
1. [noun] the earth, together with all of its countries and peoples
2. [noun] a particular region or group of countries
3. [noun] human and social interaction

const fetch=typeof窗口!='未定义的“?window.fetch:require(“节点fetch”)
const app_id=“f84663ce”//插入你的应用程序Id
const app_key=“9d0cc4ee0694e65386b9bfd69cba3aba”//插入应用程序密钥
const fields=“定义”;
const strictMatch=“false”;
异步函数lookupDefs(wordId='ace'){
常量url=https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/“+wordId+”?字段=“+fields+”&strictMatch=”+strictMatch;
常量选项={
方法:“获取”,
标题:{
“应用程序id”:应用程序id,
“应用程序密钥”:应用程序密钥
}
};
const response=等待获取(url、选项);
返回response.json();
}
(异步()=>{
for(连续词['hello','world']){
const res=等待查找定义(word);
console.log(word);
for(res.results的常数结果){
for(result.lexicalEntry的常量条目){

对于(让我=0;我为什么不用JavaScript重新编写python文件的小请求?这很容易,只要利用
节点获取
npm模块。我支持@Tenclea的想法。用一种语言编写所有代码比让两个程序相互通信更容易。使用JS获取数据应该很简单。@Tenclea,我刚刚编辑了这个问题,请看;)@RohitGarg一旦您提出请求并将其转换为json,请尝试访问response.body,您要搜索的应该是there@RohitGarg您是否尝试在响应上运行
JSON.parse(yourVariable)
const fetch = typeof window !== 'undefined'?window.fetch:require("node-fetch")

const app_id = "f84663ce"; // insert your APP Id
const app_key = "9d0cc4ee0694e65386b9bfd69cba3aba"; // insert your APP Key
const fields = "definitions";
const strictMatch = "false";

async function lookupDefs (wordId = 'ace') {
  const url = 'https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/' + wordId + '?fields=' + fields + '&strictMatch=' + strictMatch;
  const options = {
    method: "GET",
    headers: {
      'app_id': app_id,
      'app_key': app_key
    }
  };

  const response = await fetch(url, options);
  return response.json();
}

(async () => {
    for (const word of ['hello', 'world']) {

      const res = await lookupDefs(word);
      console.log (word);
      for (const result of res.results) {
        for (const entry of result.lexicalEntries) {
          for (let i=0; i<entry.entries[0].senses.length; i++) {
          const sense = entry.entries[0].senses[i];
          const cat = entry.lexicalCategory.id;
          console.log(`${i+1}. [${cat}] ${sense.definitions.join(', ')}`);
        }
      }
    }
  }
})()