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)
Related
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 have created a bot (using python-telegram-bot) that upon choosing a type of query, the bot should randomly choose one of the available strings as the reply.
My function to create replies is as follows:
def generate_reply():
replies = """
Hello
Goodbye
Thanks!
Your welcome!
See you around!""".splitlines()
r = random.choice(replies).strip()
return r
And the functions to reply to the users are as follows:
#Inline Reply
def inlinequery(update, context):
query = update.inline_query.query
results = [InlineQueryResultArticle(id=uuid4(), title="Interact",
input_message_content=InputTextMessageContent(
generate_reply()))]
update.inline_query.answer(results)
#Normal reply
def reply(update, context):
update.message.reply_text(generate_reply())
And after creating the bot I add it to the bot using:
dp.add_handler(CommandHandler("reply", reply))
dp.add_handler(InlineQueryHandler(inlinequery))
when I use /reply in chat it works as intended, but wherever I use an inline command in a chat with another user or a group, the random choice apparently stops working.How can I get around this problem?
I found out the answer to my question. Apparently Telegram caches the answers to similar inline queries for some time. For this to work correctly you should set cache_time to something you'd like, in my case 0.
#Inline Reply
def inlinequery(update, context):
query = update.inline_query.query
results = [InlineQueryResultArticle(id=uuid4(), title="Interact",
input_message_content=InputTextMessageContent(
generate_reply()))]
update.inline_query.answer(results, cache_time=0)
What was simple in Webex now seems fairly complicated in the Microsoft world.
What I specifically am looking to do is:
Create a bot in the Azure Bot Framework (Done)
Identify recipient ids using the botbuilder sdk using the recipient email
Use Botframework-Connector to individually identify these recipients, create new conversations, and proactively message them
This is what I have been using so far
https://pypi.org/project/botframework-connector/
from botbuilder.schema import *
from botframework.connector import ConnectorClient
from botframework.connector.auth import MicrosoftAppCredentials
APP_ID = 'azure_bot_app_id'
APP_PASSWORD = 'azure_bot_app_password'
SERVICE_URL = 'azure_bot_messaging_endpoint'
CHANNEL_ID = 'msteams'
BOT_ID = 'azure_bot_subscription_id'
RECIPIENT_ID = 'msteams_individual_user_id'
credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
connector = ConnectorClient(credentials, base_url=SERVICE_URL)
conversation = connector.conversations.create_conversation(ConversationParameters(
bot=ChannelAccount(id=BOT_ID),
members=[ChannelAccount(id=RECIPIENT_ID)]))
connector.conversations.send_to_conversation(conversation.id, Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text='Hello Person!'))
Is this even close to the right approach?
This was the easiest way I found to make it work.
from config import DefaultConfig
from botframework.connector.connector_client import ConnectorClient
from botframework.connector.models import ConversationParameters
from botframework.connector.auth.microsoft_app_credentials import MicrosoftAppCredentials
from botbuilder.core import MessageFactory
from botbuilder.schema import ChannelAccount
CONFIG = DefaultConfig()
recipient_id = <<RECIPIENT_ID>>
to = ChannelAccount(id=recipient_id)
bot_channel = ChannelAccount(id='msteams')
MicrosoftAppCredentials.trust_service_url(CONFIG.SERVICE_URL)
credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
conn_client = ConnectorClient(credentials, CONFIG.SERVICE_URL)
message_activity = MessageFactory.text(f"Personal message from the Bot!");
conversation_params = ConversationParameters(members=[to], channel_data={ 'tenant': { 'id': CONFIG.TENANT_ID } })
conversation = conn_client.conversations.create_conversation(conversation_params)
conn_client.conversations.send_to_conversation(conversation.id, message_activity)
It is easy to infer all the uppercase variables.
The <<RECIPIENT_ID>> is the MS Teams ID of the user you want to send the message.
Hope this helps.
MSFT does not provide good examples in Python.
With a cursory glance it looks ok (I don't work in Python so can't actually run the example). One thing that does look missing in the TrustServiceUrl call. See here for details.
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")
I am writing a telegram bot in Python. I want to send messages with bold letters. I tried to inclose message inside both * and **, but it does not solve the problem.
Is there a function for mark up or HTML formatting or a way to do it?
You should use:
bot.send_message(chat_id=chat_id, text="*bold* Example message",
parse_mode=telegram.ParseMode.MARKDOWN)
Or:
bot.send_message(chat_id=chat_id, text='<b>Example message</b>',
parse_mode=telegram.ParseMode.HTML)
More info at:
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#message-formatting-bold-italic-code-
This is a little bit late. But i hope to be helpful for others:
import telepot
token = 'xxxxxxxxxxxxxxx' # Your telegram token .
receiver_id = yyyyyyyy # Bot id, you can get this by using the next link :
https://api.telegram.org/bot<TOKEN>/getUpdates. Note that you should
replace <TOKEN> with your token.
bot = telepot.Bot(token)
message = "*YOUR MESSAGE YOU WENT TO SEND.*" #Any characters between ** will be
send in bold format.
bot.sendMessage(receiver_id, message , parse_mode= 'Markdown' )