Telethon send image with spoiler - python

How can I send image with spoiler in telethon?
I use telethon-1.27.0.
This is the code I'm using:
client.send_message(user, file="/something.png")
I tried to use has_spoiler=True but got an error message
send_message() got an unexpected keyword argument 'has_spoiler' or 'spoiler' and etc.
in sendmessage i found that parameter - Message sent. Return Value Message(id=123, peer_id=PeerUser(user_id=123), date=datetime.datetime(2023, 2, 5, 23, 11, 49, tzinfo=datetime.timezone.utc), message='123', out=True, mentioned=False, media_unread=False, silent=False, post=False, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, noforwards=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=MessageMediaPhoto(spoiler=False, photo=Photo(id=5982148115249082446

You will need to use Telethon v1.27 or greater, and then manually construct the correct media (in this case, InputMediaUploadedPhoto):
from telethon import TelegramClient, types
...
file = ... # path to your file 'photo.png' or file object
uploaded = await client.upload_file(file)
await client.send_file(chat, types.InputMediaUploadedPhoto(
uploaded,
spoiler=True,
))

The documentation explains how to send spoilers.
https://docs.telethon.dev/en/stable/examples/working-with-messages.html#sending-spoilers-hidden-text
The current markdown and HTML parsers do not offer a way to send spoilers yet. You need to use MessageEntitySpoiler so that parts of the message text are shown under a spoiler.
The simplest way to do this is to modify the builtin parsers to support sending these new message entities with the features they already provide.
The cited
recipe
shows how to define parse / unparse methods in class CustomMarkdown.
When it sees [hidden text](spoiler) and finds a literal
match on "spoiler" it edits in a MessageEntitySpoiler
object that will produce the desired effect.

Related

Need telegram bot to edit a function from another file

As the title says. I need my telegram bot to take user input, and use that to change some values on another function from another file. I already got the file to be successfully run from the bot, but I can't figure out how to change values first. I am using Python-Telegram-bot.
here is the code I need to edit that is in a separate file (call.py)
call = client.calls.create(
machine_detection='Enable',
url='https://ngrok.io/main',
to='',
from_=''
)
I need to edit the "to" and "from" field(s) in this code above.
The code I use to run this from my bot is as follows:
def update(update, context):
update.message.reply_text('Enter number :\n'
'e.g. 18004585478\n')
update.message.reply_text('Calling...')
exec(open("call.py").read())
I am pretty new to all this so I know the code is not good at all. I have read that I should be using ConversationHandler or CommandHandler but I honestly am not sure how to implement it.
I edited the code based on what Alexey suggested and now am stuck on a similar issue.
def update(update, context):
update.message.reply_text('Enter number:\n'
'e.g. 18004585478\n'
'Number Must begin with 1')
from_number = update.message.text
update.message.reply_text('Enter number:\n'
'e.g. 18004585478\n'
'Number Must begin with 1')
to_number = update.message.text
update.message.reply_text('Calling...')
call_state = call.make_call(to_number, from_number)
The Telegram bot just runs all the code at once, it doesn't stop and wait for any input from the number fields. How do I go about implementing MessageHandler to make the bot stop and accept input to pass along to call_state, then execute call_state at the end?
You don't need to change the code, you need to use arguments to pass the data you wanted to.
In call.py you can make a funciton
def make_call(to_number, from_number):
call = client.calls.create(
machine_detection='Enable',
url='https://ngrok.io/main',
to=to_number,
from=from_number,
)
return call
In your update function just use the function by giving it the necessary values
import call
def update(update, context):
update.message.reply_text('Enter number :\n'
'e.g. 18004585478\n')
update.message.reply_text('Calling...')
call_state = call.make_call(to_number='0123456789', from_number='9876543210')
# use call_state ...
What Alexey stated ended up working with very slight modifications.
I took what Alexey posted and deleted the numbers and turned them into a variable I could edit from my other script.
def make_call(to_number, from_number):
call = client.calls.create(
machine_detection='Enable',
url='https:snip/main',
to=to_number,
from_=from_number
)
print(call.sid)
Then in the other file I defined the variables and executed them by importing the file I needed to edit by using user_data[FROM] = update.message.text and user_data[TO] = update.message.text.
then calling the funciton.
call_state = call.make_call({user_data[TO]}, {user_data[FROM]})
Dont forget to add user_data = {} at the top of your code.

ROS2, TypeError when publishing custom message to Topic (python)

I have defined a custom message: uint8[] data
The custom message is imported in my Node class with no problems: from my_shared.msg import MyMessage
In the same Node, I create the publisher with: self.my_publisher = self.create_publisher(MyMessage, 'topic_in', 200)
and I publish the message with: self.my_publisher.publish(my_msg)
my_msg is built in the following way:
payload_bitstream = np.fromstring(my_data, np.uint8)
my_msg = payload_bitstream.tolist()
Sadly, I get a TypeError: File "/opt/ros/eloquent/lib/python3.6/site-packages/rclpy/publisher.py", line 68, in publish raise TypeError() TypeError
Could you help out with this if you know what I am doing wrong pls?
Thanks in advance, G.
The issue is in your assignment of my_msg, which is an instance of the class MyMessage containing attributes defined in the my_shared.msg file, namely my_msg.data which has type of uint8[]. It's correct that you did payload_bitstream.tolist() to get a list of native python ints with uint8 values, but you need to assign it to the data attribute. TL;DR:
my_msg.data = payload_bitstream.tolist()

PRAW Errors updating to new Python Distro

So I am trying to create a bot that cross posts from a sub (r/pics) to (r/polpics) using a bit of code from u/GoldenSights. I upgraded to a new python distro and I get a ton of errors, I don't even know where to begin. Here is the code (formatting off, error lines bold):
Traceback (most recent call last):
File "C:\Users\tonyc\AppData\Local\Programs\Python\Python36-32\Lib\site-
packages\praw\subdump.py", line 84, in <module>
r = praw.Reddit(USERAGENT)
File "C:\Users\tonyc\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\praw\reddit.py", line 150, in __init__
raise ClientException(required_message.format(attribute))
praw.exceptions.ClientException: Required configuration setting 'client_id'
missing.
This setting can be provided in a praw.ini file, as a keyword argument to the `Reddit` class constructor, or as an environment variable.
This seems to be related to USERAGENT setting. I don't think I have that configured right.
USERAGENT = ""
# This is a short description of what the bot does. For example
"/u/GoldenSights' Newsletter bot"
SUBREDDIT = "pics"
# This is the sub or list of subs to scan for new posts.
# For a single sub, use "sub1".
# For multiple subs, use "sub1+sub2+sub3+...".
# For all use "all"
KEYWORDS = ["It looks like this post is about US Politics."]
# Any comment containing these words will be saved.
KEYDOMAINS = []
# If non-empty, linkposts must have these strings in their URL
This is the error line:
print('Logging in')
r = praw.Reddit(USERAGENT) <--here, this is error line 84
r.set_oauth_app_info(APP_ID, APP_SECRET, APP_URI)
r.refresh_access_information(APP_REFRESH)
Also in Reddit.py :
raise ClientException(required_message.format(attribute)) <--- error
praw.exceptions.ClientException: Required configuration setting 'client_id'
missing.
This setting can be provided in a praw.ini file, as a keyword argument to
the `Reddit` class constructor, or as an environment variable.
Firstly, you're going to want to have your API credentials stored externally in your praw.ini file. This makes things a lot more secure, and looks like it might go some way to fixing your issue. Here's what a completed praw.ini file looks like, including the useragent, so try to replicate this.
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True
# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com
# The URL prefix for regular requests.
reddit_url=https://www.reddit.com
# The URL prefix for short URLs.
short_url=https://redd.it
[appname]
client_id=IE*******T14_w
client_secret=SW***********************CLY
password=******************
username=appname
user_agent=web:appname:1.0.0 (by /u/username)
Let me know how things go after you sort this out.

Why does createNote on Evernote Python API fail with errorcode 5 (DATA_REQUIRED) though data seems to be provided?

I'm new to the Evernote python 2.x API and I'm working on some examples. I managed to create a note in the sandbox, but I failed in creating a note with attachment. I followed the example code given in https://dev.evernote.com/doc/articles/creating_notes.php and I end up calling
try:
note = noteStore.createNote(authToken, ourNote)
except Errors.EDAMUserException, edue:
## Something was wrong with the note data
## See EDAMErrorCode enumeration for error code explanation
## http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
print "EDAMUserException:", edue
return None
The parameter ourNote was printed as
Note(contentHash=None, updated=None, created=None, deleted=None, contentLength=None, title='testtitel2', notebookGuid=None, content='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>testbody<br /><br />Attachment with hash 3430623163666630303562663662393263386539663366613134636630323736: <br /><en-media type="text/plain" hash="3430623163666630303562663662393263386539663366613134636630323736" /><br /></en-note>', tagNames=None, updateSequenceNum=None, tagGuids=None, active=None, attributes=None, guid=None, resources=[Resource(noteGuid=None, height=None, width=None, alternateData=None, mime='text/plain', updateSequenceNum=None, duration=None, attributes=ResourceAttributes(recoType=None, sourceURL=None, cameraMake=None, timestamp=None, altitude=None, clientWillIndex=None, longitude=None, fileName=None, attachment=None, latitude=None, applicationData=None, cameraModel=None), guid=None, data=Data(body='This is the content of testfile, aaa, bbb\\n\n', bodyHash='40b1cff005bf6b92c8e9f3fa14cf0276', size=44), active=None, recognition=None)])
I'm getting
EDAMUserException: EDAMUserException(errorCode=5, parameter='[3430623163666630303562663662393263386539663366613134636630323736]')
which says DATA_REQUIRED. What exactly is wrong or missing?
From the error message, you are missing a resource that is in your ENML. See this sample code to make sure you are handling your file attached to your note properly.
I resolved my issue by changing line 20 in the sample code from
hexhash = binascii.hexlify(resource.data.bodyHash)
to
hexhash = resource.data.bodyHash
which makes it work. I don't know what the hexlify() was intended for here. I will ask the Evernote guys. The parameter in the error message in my original post was the "hexlified" hash. Btw: in order to determine the bodyHash I'm using the way described here.

Skype4Py - How to successfully add a contact?

I'm working to implement a few fun features with a SkypeBot, and one of the features I'd like to implement is the ability to add a new contact. While reviewing the Skype4Py docs, I note this method:
http://skype4py.sourceforge.net/doc/html/Skype4Py.client.Client-class.html#OpenAddContactDialog
I am using the following code to try to access this:
sky = Skype4Py.Skype()
client = Skype4Py.client.Client(sky)
sky.Attach()
client.OpenAddContactDialog("test")
However, when trying to utilize almost anything from Skype4py.client.Client I get a timeout with the traceback:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/client.py", line 164, in OpenDialog
self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/skype.py", line 276, in _DoCommand
self.SendCommand(command)
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/skype.py", line 778, in SendCommand
self._Api.send_command(Command)
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/api/darwin.py", line 395, in send_command
raise SkypeAPIError('Skype command timeout')
SkypeAPIError: Skype command timeout
I receive this timeout error on every method I try to access within the client class. (ie:
OpenAuthorizationDialog, OpenCallHistoryTab, OpenContactsTab). Am I accessing this method incorrectly, or perhaps the method is not supported for newer versions of Skype? Any help with getting this working, or a method that adds contacts via Skype4Py successfully will be very appreciated.
sky = Skype4Py.Skype()
sky.Attach()
client = Skype4Py.client.Client(sky)
client.OpenAddContactDialog("Torxed")
Trying a few things out but i'm 99% sure that's the order in which you have to do things.
Otherwise you will time out because the attachment needs time to attach before you start executing things towards the API.
Also take a look at:
http://skype4py.sourceforge.net/doc/html/Skype4Py.user.User-class.html#SetBuddyStatusPendingAuthorization
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.SkypeEvents-class.html#UserAuthorizationRequestReceived
Also you might be going about this the wrong way.
Adding a skype user directly, is not how Skype works.
search
request add with a message
wait for authorization
So, try one of the following:
(one is a asyncore way of searching and adding as they pop up, the other will bunch your results)
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.Skype-class.html#AsyncSearchUsers
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.Skype-class.html#SearchForUsers
So try:
sky = Skype4Py.Skype()
sky.Attach()
print skyp.SearchForUsers('Torxed')
Should get you a handle to add me for instance.
Within the object that you recieve, there will be an option to add me for instance.
#Torxed's answer was right, but here's more information in case anyone wasn't able to make it the last mile.
I was able to add a contact in this way:
import Skype4Py
sky = Skype4Py.Skype()
sky.Attach()
requestMessage = "Please accept my request!"
searchResults = sky.SearchForUsers('echo123')
firstResult = searchResults[0]
firstResult.SetBuddyStatusPendingAuthorization(requestMessage)
Do be careful, though as this merely adds the FIRST result returned by the search. If you have the username exact, it should be fine.

Categories

Resources