如何在JS和Python之间通信?

2024-09-29 19:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个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),它的输出如下: chaotic output

如果有人能告诉我如何使用返回的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);
    });
});

Tags: 文件key代码inpyclientidapp
3条回答

通过使用node-fetchnpm模块在JS中重新编码程序,在注释中解决了问题

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

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

当您在本地计算机上完成应用程序时,这里是deploying python application on HerokuDeploy Python Flask App on Heroku 上的指南

下面是一个工作的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 !== '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(', ')}`);
        }
      }
    }
  }
})()

相关问题 更多 >

    热门问题