Im coding an bot which searches and sends files search command is already infuction but send command won't work here is my code appreciate any help
#bot.command()
async def search(ctx, *, file_name):
search_result = ''
from os import listdir
for file in listdir('ArkFiles/Dinos'):
if file_name in file.lower():
search_result = search_result+'\n'+file
if search_result == 'Search Results:':
await ctx.reply('Error: Not matched with any file.')
else:
embed = discord.Embed(title=f"Here is a list of files I found in the current Ark files that include '{file_name}':")
embed.add_field(name='** **', value= search_result, inline=False)
await ctx.reply(embed=embed)
#bot.command(pass_context=True)
async def sendachatina(ctx):
area=ctx.message.channel
await bot.send_file(area, "ArkFiles/Dinos/Achatina.zip", filename="Achatina.zip",content="Here you go:")
I don't want it that i have to do a command for every single file i want it that i have to input correctly and it automatically outputs the correct file.
I am not sure how to send the file by your style of coding but follow the below code it works for sure
await ctx.send(file=discord.File("ArkFiles/Dinos/Achatina.zip"),content="Here you go:")
This is the syntax of the send in discord.py. There is no option to change file there
await ctx.send(content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None, allowed_mentions=None)
where
content (str) – The content of the message to send.
wait (bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a WebhookMessage if set to True.
username (str) – The username to send with this message. If no username is provided then the default username for the webhook is used.
avatar_url (Union[str, Asset]) – The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used.
tts (bool) – Indicates if the message should be sent using text-to-speech.
file (File) – The file to upload. This cannot be mixed with files parameter.
files (List[File]) – A list of files to send with the content. This cannot be mixed with the file parameter.
embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.
embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed parameter.
allowed_mentions (AllowedMentions) – Controls the mentions being processed in this message.
This is the documentation of discord.py if you want you can refer it
here
Related
so im playing a little bit around with my telegram bot, now im already able to send normal messages and pictures. But now i want to be able to send pre recorded voice messages as an answer. In the documentation it says to use send_voice for this matter and it recommends using the file_id of a file thats already on the telegram servers. So thats what i did i send a voice message to the #RawDataBot and he returned to me the file_id of the voice message.
Problem is: When i try to trigger it i get the following error: telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: wrong file identifier/HTTP URL specified
Any ideas here on what i might be doing wrong? Here is the relevant code:
import telebot
API_KEY = <MY_API_KEY>
bot = telebot.TeleBot(API_KEY)
#start
#bot.message_handler(commands=['start'])
def start (message):
bot.send_message(message.chat.id,Textstart)
#bot.message_handler(commands=['pic'])
def start (photo):
bot.send_photo(photo.chat.id, "https://de.wikipedia.org/wiki/Zeus#/media/Datei:Zeus_Otricoli_Pio-Clementino_Inv257.jpg")
#here is the part where he is supposed to send the voice message if someone types in /audio
#bot.message_handler(commands=['audio'])
def start (voice):
bot.send_voice(voice.chat.id,"AwACAgIAAxkBAAEWjl5i5bjyudWAM9IISKWhE1Gjs5ntQgACLx8AApcNKEv97pVasPhBoCkE",)
bot.polling()
There are multiple reasons, but I think it is because of these:
file_id is unique for each individual bot and can't be transferred from one bot to another.
file_id uniquely identifies a file, but a file can have different valid file_ids even for the same bot.
See here.
#dp.message_handler(content_types=types.ContentType.DOCUMENT)
async def scan_message(file: types.File):
print("downloading document")
file_path = file.file_path
destination = r"C:\users\aleks\PycharmProjects\pythonProject\file.pdf"
destination_file = bot.download_file(file_path, destination)
print("success")
I would like to be able to download a file (in this case it is pdf) that was sent to my bot by the user. But the problem is that the bot doesn't even recognize a file (when I send a file, it doesn't even print "downloading document")
TL;DR
I hope you're using aiogram v2.x.
Make sure that's the only handler for types.ContentType.DOCUMENT without filters and your bot can get needed updates, then:
#dp.message_handler(content_types=types.ContentType.DOCUMENT)
async def scan_message(message: types.Message):
print("downloading document")
destination = r"C:\users\aleks\PycharmProjects\pythonProject\file.pdf"
await message.document.download(destination)
print("success")
Detailed
Everything described below applies to stable aiogram v2.x.
aiogram.Dispatcher class parses raw telegram Update and sends it parsed and unpacked to corresponding handler, e.g. dp.message_handler will receive aiogram.types.Message for updates containing message, dp.callback_query_handler will receive aiogram.types.CallbackQuery for updates containing callback_query and so on. In your case you are expecting aiogram.types.File, which is wrong. Then dispatcher checks filters and calls corresponding handlers in registration order and stops dispatching if any handler was called.
Consider the following example:
# Some code omitted in favor of brievity
#dp.message_handler()
async def handle1(msg: types.Message):
print("handled 1")
#dp.message_handler()
async def handle2(msg: types.Message):
print("handled 2")
You send any text message then look at bot's console. There will only "handled 1" be printed because it was the first matching handler and only one handler is called.
Bots have so-called "Privacy mode" in group chats, so not every message comes to your bot in a group. This is not the case in private (direct) messages, so it's better to test your bot in private. You can read more about Privacy mode in official Bot API docs: https://core.telegram.org/bots#privacy-mode.
It's better and more readable to use shortcuts which are contained in each class, e.g. you can .reply() or .answer() to a aiogram.types.Message, which is a shortcut for aiogram.Bot.send_message(). Same with downloading file, you can just use .download() on aiogram.types.Document, aiogram.types.PhotoSize and so on. You can find more downloadable types by looking for classes that implement aiogram.types.mixins.Downloadable.
All .download() methods return destination where the file was saved. If you pass your own optional destination as the first argument to the method, it'll be useless to get it back as you already know it.
So, after these modifications, you'll get the code as in TL;DR section.
You did not specify version of aiogram. I guess it is 2.x.
All asynchronous function registered, as message handler must take the first positional parameter received message. If you like type hints you must to specify your function as
async def scan_message(message: types.Message):
for download your document you need just:
destination_file = await message.document.download(destination)
so correct handler for download document is:
async def scan_message(message: types.Message):
print("downloading document")
destination = r"C:\users\aleks\PycharmProjects\pythonProject\file.pdf"
destination_file = await message.document.download(destination)
print("success")
I am trying to make a bot for Telegram using pyTelegramBotAPI, it is a store to download Windows Applications, because of the 50MB limit of sending the telegram. I send the file as a user and get the File_ID, which causes the bot to send 2GB files. Each program has a file.txt with your File_ID written.
The bot reads vlc.txt, sets it as a variable and sends the file.
But the program has an error.
"2020-12-19 21:06:09,106 (init.py:489 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: wrong remote file identifier specified: Wrong character in the string""
When I manually put the File_ID in the code, it works perfectly, it can't get the file_id from the variable, and I sent the program to print to make sure the variable contains the File_ID written correctly. What could be causing this?
def selecionou(query):
#pretreatment definition
download = query.data.count('down')
info = query.data.count('info')
prints = query.data.count('prints')
#app name treatment
if download > 0:
name = query.data.replace("down.","")
print(name)
file_id = open(f'/home/flaipy/PycharmProjects/Lucas/apps/{name}.txt','r')
file_id = file_id.read()
print(file_id)
#order type treatment
if download > 0:
print(file_id)
bot.send_document(query.message.chat.id, file_id)
I was reading w3schools from the "read ()" method in python, and saw that there is an argument to limit the number of characters, I put 70 and it worked, even in the txt file having no space. It is a tip for those who go through the same problem.
file_id = file_id.read(70)
I already tried search this in Google. But I couldn't find the answer. I want to bot send user's location. Here is the final version(It doesn't work):
markup_request = ReplyKeyboardMarkup(resize_keyboard=True).add(
KeyboardButton('Send your contact ☎️', request_contact=True)
).add(
KeyboardButton('Send your location 🗺️', request_location=True)
)
#dp.message_handler(commands=['location'])
async def message_for_start(message: types.Message):
await message.reply('Location', reply_markup=markup_request)
Firstly, check your imports.
Secondly, use other methods, instead of try <send_message> or . Reason is updating of aiogram library.
My key is ready to go to make requests and get speech from text from Google.
I tried these commands and many more.
The docs offer no straight forward solutions to getting started with Python that I've found. I don't know where my API key goes along with the JSON and URL
One solution in their docs here is for CURL.. But involves downloading a txt after the request that has to be sent back to them in order to get the file. Is there a way to do this in Python that doesn't involve the txt I have to return them?
I just want my list of strings returned as audio files.
(I put my actual key in the block above. I'm just not going to share it here.)
Configure Python App for JSON file and Install Client Library
Create a Service Account
Create a Service Account Key using the Service Account here
The JSON file downloads and save it securely
Include the Google Application Credentials in your Python App
Install the library: pip install --upgrade google-cloud-texttospeech
Using Google's Python examples found:
https://cloud.google.com/text-to-speech/docs/reference/libraries
Note: In Google's example it is not including the name parameter correctly.
and
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/texttospeech/cloud-client/quickstart.py
Below is the modified from the example using google app credentials and wavenet voice of a female.
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/home/yourproject-12345.json"
from google.cloud import texttospeech
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text="Do no evil!")
# Build the voice request, select the language code ("en-US")
# ****** the NAME
# and the ssml voice gender ("neutral")
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
name='en-US-Wavenet-C',
ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)
# Select the type of audio file you want returned
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(synthesis_input, voice, audio_config)
# The response's audio_content is binary.
with open('output.mp3', 'wb') as out:
# Write the response to the output file.
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
Voices,Name, Language Code, SSML Gender, Etc
List of Voices: https://cloud.google.com/text-to-speech/docs/voices
In the above code example I changed the voice from Google's example code to include the name parameter and to use the Wavenet voice (much improved but more expensive $16/million chars) and the SSML Gender to FEMALE.
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
name='en-US-Wavenet-C',
ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)
Found the answer and lost the link among 150 Google documentation pages I had open.
#(Since I'm using a Jupyter Notebook)
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/Path/to/JSON/file/jsonfile.json"
from google.cloud import texttospeech
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text="Hello, World!")
# Build the voice request, select the language code ("en-US") and the ssml
# voice gender ("neutral")
voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
# Select the type of audio file you want returned
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(synthesis_input, voice, audio_config)
# The response's audio_content is binary.
with open('output.mp3', 'wb') as out:
# Write the response to the output file.
out.write(response.audio_content)
print('Audio content written to file "output.mp3"')
My time consuming pursuit was to try to send the request through a JSON with Python, but this appears to be through there own modules, which works fine.
Notice the default voice gender is 'neutral'.
If you would like to avoid using the google Python API, you can simply do this:
import requests
import json
url = "https://texttospeech.googleapis.com/v1beta1/text:synthesize"
text = "This is a text"
data = {
"input": {"text": text},
"voice": {"name": "fr-FR-Wavenet-A", "languageCode": "fr-FR"},
"audioConfig": {"audioEncoding": "MP3"}
};
headers = {"content-type": "application/json", "X-Goog-Api-Key": "YOUR_API_KEY" }
r = requests.post(url=url, json=data, headers=headers)
content = json.loads(r.content)
It is similar to what you did but you need to include your API key.