Last week I installed the Telegram application on my Raspberry Pi and set up a script to send me notifications on time (with crontab). But as I have to enter a Token from my Bot and a chat_id of my Telegram Account I want to store them one time in different files so I only have to change it in one file if they ever change. So far my code looks like this:
telepot.py:
import telepot
import values
with open("values.py", "r") as valuesFile:
chat_id, Token = valuesFile.readlines()
bot = telepot.Bot('TOKEN')
bot.sendMessage(chat_id, 'message')
values.py:
chat_id = 'ChatID'
Token = 'TOKEN'
But I haven't figured out how to get the information from my other files. I have looked on the internet but I'm not really good a programming like at all so I hoped somebody could help me with finding the right command to import the two strings from my files and use them as the declaration for chat_id and TOKEN.
Your question is rather unclear. Are you importing the values and tokens from a python file? A text file?. I will guide you through a few examples.
If you want to import the values from another python file (let's call it values.py and let's assume it's in the same directory as the script you sent (telepot.py))
values.py
chat_id = 'YOUR_CHAT_ID'
TOKEN = 'YOUR_TOKEN'
telepot.py
import values
import telepot
bot = telepot.Bot(values.TOKEN)
Now, let's assume the values you need are in a text file, values.txt that looks like:
TOKEN
CHAT_ID
telepot.txt
import telepot
with open("values.txt", "r") as valuesFile:
chatId, Token = valuesFile.readlines()
bot = telepot.Bot(Token)
bot.sendMessage(chatId, "This is a message")
Related
I'm newbie at Python. I want to parse certain dialog(contains only captions to pics) with Pyrogram. But if i use iter_history() methog it returns none if message contains pic+text.Like that.
import asyncio
from pyrogram import Client
app = Client("my_acc")
target = "dialog_example" # "me" refers to your own chat (Saved Messages)
with app:
for message in app.iter_history(target):
print(message.text)
None
Process finished with exit code 0
message.text is a message's text. If you want the caption of a message (or document rather), access message.caption.
This is for a discord bot to translate languages using google translate API after emoji flag for specific language was chosen and the reaction would be to translate to that language, for ex. US Flag would translate the text to English.
Code for importing the json file with the emoji names and values:
import json
with open('emoji_flags.json', 'r') as file:
data = json.load(file)
This is the code I was working with before using if and elif but I was told that would be an issue which needed to change. How can I change the code to access the json file, find the correct language name/value, and then translate the correct language based on choosing the right one. I am new to all this so I need to learn more python to be able to understand what code would work for this but any help would be appreciated:
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
if reaction.emoji == '🇺🇸':
translation = translate_text('en', reaction.message.content)
Data from the json file, I am starting out with English to make sure it works correctly before adding other languages:
{
":flag_us:" : "en"
}
To read from a json file, you were correct that you first have to open it using file = open() and then you can read the file into a dict with data = json.load(file), and at the end you will have to close the file again using file.close(). To simplify the process with closing the file, you did correctly use the with keyword, but you need to indent the code that the file should be opened for:
with open(emoji_flags.json) as json_file:
data = json.load(json_file)
Now data is a dictionary from which you can later extract data. But first we want to get the emoji:
emoji = payload.emoji.name
Also you should use on_raw_reaction_add, since on_reaction_add only works for cached messages.
Since there is currently no way of getting the emoji name in the way it's in discord (:flag_us:), you will have to change the structure of your json file to have the emojis as keys:
{
"🇺🇸" : "en"
}
Note that the emoji looks different in different platforms and apps, even tho it's the same.
Then you can access the language code with
try: #use try except if it's a different emoji
language_code = data[emoji]
except KeyError:
pass
This all together would be
#bot.event
async def on_raw_reaction_add(payload):
with open(emoji_flags.json) as json_file:
data = json.load(json_file)
emoji = payload.emoji.name
try: #use try except if it's a different emoji
language_code = data[emoji]
channel = await bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
translation = translate_text(language_code, message.content)
except KeyError:
pass
References:
PartialEmoji
on_raw_reaction_add
RawReactionActionEvent
I'm currently working on a bot that, messages Users in a given json-file in certain time intervals. I tried this code but it doesn't do what it's supposed to nor does it give me an error I could work with.
#tasks.loop(seconds=10)
async def dm_loop():
with open("users.json" "r") as file:
users = json.load(file)
for stgru in users:
for i in users[stgru]:
user = await client.fetch_user(i)
await user.send("hello")
And just in case you're wondering: the short time Intervals and the unnecessary message: "hello", ist just for testing purposes. The "users.json"-file, mentioned in the code, has a format like this:
{
"724": ["name1#2819", "name2#2781", "name3#2891"],
"727": [],
"986": ["name4#0192"],
"840": ["name5#1221", "name6#6652"],
"798": ["name7#3312", "name8#8242", "name9#1153", "name10#3318"]
}
I already added the "dm_loop.start()"-method to my "on_ready()" but it's not working at all.
I'd be so glad if anyone could help me out here. Thanks
According to the docs, fetch_user looks up users by their ID, so you need to store the user ID instead of the user name.
https://discordpy.readthedocs.io/en/master/ext/commands/api.html?highlight=fetch_user#discord.ext.commands.Bot.fetch_user
Otherwise you can create your own UserConverter. Here's an example on how you would do that.
from discord.ext import commands
[...]
user_name = "some_tag#1234"
user = await commands.converter.UserConverter().convert(ctx, argument=user_name)
await user.send("Hello")
I do really recommend the first option though, it is a lot simpler. Since you would have to create a custom context if you are not using this in a command i believe.
I have a telegram bot (developed in python) and i wanna to send/upload photo by it from images that are in my computer.
so i should do it via multi part form data.
but i don't know ho to do it. also i didn't find useful source for this on Internet and on telegram documentation .
i tried to do that by below codes. but it was wrong
data = {'chat_id', chat_id}
files = {'photo': open("./saved/{}.jpg".format(user_id), 'rb')}
status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto", data=data, files=files)
can anyone help me?
Try this line of code
status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id=" + data['chat_id'], files=files)
Both answers by Delimitry and Pyae Hlian Moe are correct in the sense that they work, but neither address the actual problem with the code you supplied.
The problem is that data is defined as:
data = {'chat_id', chat_id}
which is a set (not a dictionary) with two values: a string 'chat_id' and the content of chat_id, instead of
data = {'chat_id' : chat_id}
which is a dictionary with a key: the string 'chat_id' and a corresponding value stored in chat_id.
chat_id can be defined as part of the url, but similarly your original code should work as well - defining data and files as parameters for requests.post() - as long as both data and files variables are dictionaries.
You need to pass chat_id parameter in URL:
files = {'photo': open('./saved/{}.jpg'.format(user_id), 'rb')}
status = requests.post('https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id={}'.format(chat_id), files=files)
Your problem already solved by aiogram python framework.
This is full example. Just edit TOKEN and PHOTO_PATH, run the code and send /photo command to the bot :)
from aiogram import Bot, Dispatcher, executor
from aiogram.types import InputFile, Message
TOKEN = "YourBotToken"
PHOTO_PATH = "img/photo.png"
bot = Bot(TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(commands=["photo"])
async def your_command_handler(message: Message):
photo = InputFile(PHOTO_PATH)
await message.answer_photo(photo)
if __name__ == '__main__':
executor.start_polling(dp)
I'm creating a telegram bot that searchs for words in a online dictionary, the problem comes when I need to create the command in Telegram for searching in that dictionary, at the momment I have this:
from rae import Drae
drae = Drae()
if text.startswith('/'):
if text =='/define':
drae.search(u' ') # The problem is here, I don't know how to implement the command and the word who the client wants to search.
setEnabled(chat_id, True)
I'm using this Telegram API in Python: https://github.com/yukuku/telebot
And this API for the Dictionary: https://github.com/dialelo/rae-1
How about this.
from rae import Drae
drae = Drae()
if text.startswith('/'):
if text.startswith('/define'):
try:
[command, data] = text.split(' ',1)
except:
send('Write: /define <word>')
meanings = drae.search(data)
reply(str(meanings))
setEnabled(chat_id, True)