google translate command? (python) - python

So I want to make a command for my discord bot that translates stuff. I'm using repl.it and the googletrans pip install code won't work for some reason. I also tried doing pip install googletrans==3.1.0a0 in the shell, but it won't work either. Is there currently a code for google translate that works in python or an updated one that works for repl.it??
here's my current code (when i try the command, it doesn't respond):
#client.command(aliases=['tr'])
async def translate(ctx, lang_to, *args):
lang_to = lang_to.lower()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument("Invalid language detected. Make sure to check if it is spelled correctly and that it is a real language.")
text = ' '.join(args)
translator = googletrans.Translator()
text_translated = translator.translate(text, dest=lang_to).text
await ctx.send(text_translated)```

Hey try to Install google translator version 4.0.0rc1!
pip install googletrans==4.0.0rc1
My code:
#bot.command()
async def trans(ctx, lang, *, args):
t= Translator()
a= t.translate(args, dest=lang)
tembed= discord.Embed(title=f'Translating Language....', description=f'Successfully translated the text below :point_down: \n \n**{a.text}**', color=discord.Colour.random())
await ctx.send(embed=tembed)
print(googletrans.LANGUAGES)

Related

Hindi Voice from Assistant

I wish to have voice assistant in Hindi. Can engine.say() accept translated text? My code is below. It speaks English text, but not Hindi text. No error occurs, however no voice occurs. (My laptop sound=100%).
Can anyone help?
import pyttsx3
from translate import Translator
engine = pyttsx3.init()
translator= Translator(from_lang="english",to_lang="hindi")
translation = translator.translate("Today is Tuesday")
print(translation)
engine.say("My first code on text-to-speech")
engine.say(translation)
engine.runAndWait()
Your code ran fine after I installed its upstream dependencies
pip3 install translate pyttsx3
when I ran it got this error
OSError: libespeak.so.1: cannot open shared object file: No such file or directory
so then I installed libespeak1 ... I am on Ubuntu so this command is
sudo apt-get install libespeak1
then below python code executed correctly and I could hear the translation
from translate import Translator
import pyttsx3
translator= Translator(from_lang="english",to_lang="hindi")
# translation = translator.translate("Today is Tuesday")
translation = translator.translate("Today is Tuesday and its the day before Wednesday")
engine = pyttsx3.init()
engine.setProperty("languages",'hi')
engine.say(translation)
engine.runAndWait()

No Audio with pyttsx3 Library in Python 3 (No errors)

Using pyttsx3 (tried versions 2.5 to current) on Visual Studios Code on Windows 10 With Python 3.10.0.
My Problem that I am currently having is that the code will run through, but no audio is being outputted. while debugging there is no pause stepping into or over the code (for parts including pyttsx3). I made sure my audio is on, and that it is working. I used a different tts library gtts and the audio worked, but I am trying to write offline. I also tried this exact code from VS code in PyCharm and I still had the same problem. Again with no errors or warnings.
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init(driverName='sapi5')
#voices = engine.getProperty('voices')
#engine.setProperty('voice', voices[0].id)
engine.say("Testing, audio")
engine.runAndWait
try:
with sr.Microphone() as source:
print('Listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
engine.say(command)
engine.runAndWait
except:
pass
print('Hello')
I also tried this block of code with no driver name and the same problem above persists
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init()
#voices = engine.getProperty('voices')
#engine.setProperty('voice', voices[0].id)
engine.say("Testing, audio")
engine.runAndWait
try:
with sr.Microphone() as source:
print('Listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
engine.say(command)
engine.runAndWait
except:
pass
print('Hello')
The two commented lines on both programs didn't change anything for me either.
I also tested the program with just pyttsx3.
import pyttsx3
engine = pyttsx3.init(driverName='sapi5')
engine.say("Testing, audio")
engine.runAndWait
and tested using 'Testing, audio' instead of "Testing, audio" and I tried single words as well.
Any help would be amazing! Thank you!
In the mean time I will try to test this(translated to work with Linux) program in Linux to see if my OS is the issue.
I will also try an older version of python to see if that is the issue. Along with python 2.
My biggest assumption is that pyttsx3 needs a earlier version of python to work, but I could also be 100% wrong about that.
You forgot to put the parentheses on engine.runAndWait. Do this: engine.runAndWait()

Visual Studio Code doesn´t move to next line usign asyncio and pyppeteer

My goal is to open an browser using pyppeteer and creating a new tab. But Visual Studio stops executing the code after the browser = await launch(headless=False) line.
But executing the same code in for Example Thonny does work.
Any Help?
Here is the code (its just an example form the internet):
import asyncio
from pyppeteer import launch
from pyquery import PyQuery as pq
async def main():
browser = await launch(headless=False)
page = await browser.newPage()
await page.goto("http://quotes.toscrape.com/js/")
doc = pq(await page.content())
print("Quotes:", doc(".quote").length)
await browser.close()
asyncio.run(main())```
Here's the result your code run in my project, which opened a blank browser window:
Open Command Palette and choose Python: Clear Internal Extension Cache.
If not help, open a new project, create a new virtual environment and select it as interpreter. See create a virtual environment.

Discord.py - change the default help command

I'm trying to change the help command to use a pagination version of help.
I understand that the following line of code removes the help command entirely:
bot.remove_command('help')
The docs/dicord.py server offer the following example as a way to change the default help command:
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command
I'm still a newbie in python, and I've only been learning rewrite for about 3 days - I'm struggling to find any working examples or an explanation that doesn't lead me back to the above code. I can't work out how to implement this into my own code - so my question is, could anyone provide further explaination into how this would be implemented using cogs?
You can use help_command=None. It delete default help command and you can create your help command. Example:
bot = commands.Bot(command_prefix='!', help_command=None)
#bot.command()
async def help(context):
await context.send("Custom help command")
If you don't set help_command=None and try to create your help command, you get this error: discord.errors.ClientException: Command help is already registered.
You don't really need to remove the command... It isn't good, using the (prefix)help commandname <- It wont appear then... If you want it embed you can do.
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
client.help_command = NewHelpName()
The built in help command is of great use

python3 running old version of script

I've changed a script by commenting out a section and adding some print statements above it for testing purposes, the problem is when I run the script from any other directory than the one it's in, python is running the old version of the script.
Clearing __pycache__ had no effect.
Here's the python script in question:
import discord
import watson
import configparser
import os
from discord.ext.commands import Bot
from getpass import getuser
print("WHY ISN'T THIS BEING CALLED!!")
#print(os.getcwd())
#os.chdir("/home/{}/discordBotStaging".format(getuser()))
#print(os.getcwd())
#if(not os.path.isfile("./config.ini")):
# print("No config file found, make sure you have one in the same directory as this python script\nexiting")
# quit()
config = configparser.ConfigParser()
config.read("./config.ini")
TOKEN = config["DEFAULT"]["DISCORD_KEY"]
BOT_PREFIX = ("!", "$")
client = Bot(command_prefix=BOT_PREFIX)
#client.command(name="memealyze",
description="When uploading image include command \"!memealyze\" | \"!Memealyze\" | \"!MemeAlyze\" | \"!ma\" as a comment",
brief="Neural network put to good use",
aliases=["Memealyze", "MemeAlyze", "ma"],
pass_context=True)
async def GetMemeContents(context):
await client.say("Sending image to the mothership, hold tight.")
if(not context.message.attachments):
await client.say(
"Couldn't find image attachement. Make sure you include \"!memealyze\" or any of it's variants as a comment when submitting an image")
return
imageUrl = str(context.message.attachments[0]["url"])
messageContent = ""
resultDict = watson.ReturnWatsonResults(imageUrl)
for key,val in resultDict.items():
messageContent += "{} : {}%\n".format(key, val)
await client.say("Done, the boys at IBM said they found this:\n" + messageContent)
client.run(TOKEN)
And here's the issue:
yugnut#RyzenBuild:~$ python3 discordBotStaging/main.py
No config file found, make sure you have one in the same directory as this python script
exiting
yugnut#RyzenBuild:~$
yugnut#RyzenBuild:~/discordBotStaging$ python3 main.py
WHY ISN'T THIS BEING CALLED!!
^Cyugnut#RyzenBuild:~/discordBotStaging$
EDITS:
#ShadowRanger suggestions:
Try moving the print above all the imports in your script.
This yields promising results, I do get output by trying this but right after that I still run into the same issue
You can't use relative paths like that if the config file is expected to be in the same directory as the script; you have to do config.read(os.path.join(os.path.dirname(__file__), 'config.ini'))
I think my ignorance is showing :^), I changed this in my script as well
After making these edits along with trying to run the script after commenting out my import configparser line I still get the same error.

Categories

Resources