Link content type to funtion on Telebot Python - py-telegram-bot-api

I am building a Telegram Bot using telebot with python. I ask users to updload a picture, for which I created a command "foto". When they do /foto, I ask them to updload a content type "photo". However, they can upload pictures regardless of the command; they just click on upload a picture and that's it. How can I link the "upoload photo" to the command, so that they can only upload a picture after writing "/foto"?
#bot.message_handler(commands=['foto']) def send_welcome(message,
chat_id):
chat_id = message.chat.id
send = bot.send_message(message.from_user.id, 'Subí tu foto.')
bot.register_next_step_handler(send, photo())
return
#bot.message_handler(content_types=["photo"]) def photo(message):
fileID = message.photo[-1].file_id
logger.info("User_id, fileID", message.from_user.id, fileID)
file_info = bot.get_file(fileID)
#print('file.file_path =', file_info.file_path)
downloaded_file = bot.download_file(file_info.file_path)
with open(f"./images/{fileID}.jpg", 'wb') as new_file:
new_file.write(downloaded_file)
send = bot.send_message(message.from_user.id, 'Foto recibida, gracias!')

As far as i know you cant restrict users from sending files
what you can do is to capture the files only after the command is used
for more info please read docs

Related

Email Pdf attachments to Google sheet

I am looking for something that allows me from a mail PDF attachment to get a data in a google sheet.
We all often get PDF attachments in our email and it will be great if we get the entire data in a google sheet.
DO let me know if there is anything like this
Explanation:
Your question is very broad and it is impossible to give a specific answer because that answer would depend on the pdf but also on the data you want to fetch from that, besides all the other details you skipped to mention.
Here I will provide a general code snippet which you can use to get the pdf from the gmail attachments and then convert it to text (string). For this text you can use some regular expressions (which have to be very specific on your use case) to get the desired information and then put it in your sheet.
Code snippet:
The main code will this one. You should only modify this code:
function myFunction() {
const queryString = "label:unread from example#gmail.com" // use your email query
const threads = GmailApp.search(queryString);
const threadsMessages = GmailApp.getMessagesForThreads(threads);
const ss = SpreadsheetApp.getActive();
for (thr = 0, thrs = threads.length; thr < thrs; ++thr) {
let messages = threads[thr].getMessages();
for (msg = 0, msgs = messages.length; msg < msgs; ++msg) {
let attachments = messages[msg].getAttachments();
for (att = 0, atts = attachments.length; att < atts; ++att) {
let attachment_Name = attachments[att].getName();
let filetext = pdfToText( attachments[att], {keepTextfile: false} );
Logger.log(filetext)
// do something with filetext
// build some regular expression that fetches the desired data from filetext
// put this data to the sheet
}}}
}
and pdfToText is a function implemented by Mogsdad which you can find here. Just copy paste the code snippet provided in that link together with myFunction I posted in this answer. Also you have some options which you can use that are very well explained in the link I provided. Important thing to note, to use this library you need to enable the Drive API from the resources.
This will get you started and if you face any issues down the road which you can't find the solution for, you should create a new post here with the specific details of the problem.

Get all App IDs of all installed Apps on LG webOS TV

i am trying to get some information about LG webOS TVs. For some home automation i would need these two information. Maybe someone can tell me where I should look for that or how to get these information:
1) I would need all the app ids from all apps which are installed on the tv. I do have some already but not all of them.
2) I also would need all the button bindings of the remote. Same as for the app ids, i know a few but not all.
Please have a look at the codes. It would be really nice if someone can provide a list or tell me how to get these.
Thank you very much!
App ID list:
"com.webos.app.hdmi1" = "HDMI-1",
"com.webos.app.hdmi2" = "HDMI-2",
"com.webos.app.hdmi3" = "HDMI-3",
"com.webos.app.hdmi4" = "HDMI-4",
"com.webos.app.today" = "Heute",
"lovefilm.de" = "Amazon Prime Video",
"googleplaymovieswebos" = "Google Play Filme",
"youtube.leanback.v4" = "YouTube",
"com.webos.app.browser" = "Webbrowser",
"com.webos.app.connectionwizard" = "Geräteanschluss",
"com.webos.app.smartshare" = "SmartShare",
"com.webos.app.miracast" = "Screen Share",
"com.webos.app.notificationcenter" = "Benachrichtigungen",
"com.palm.app.settings" = "Einstellungen",
"com.webos.app.softwareupdate" = "Software-Update",
"de.2kit.castbrowserlg" = "TV Cast"]
"com.webos.app.livetv"="TV",
"com.webos.app.tvguide"="TV Guide",
"youtube.leanback.v4" = "Youtube",
"googleplay" = "googleplay"
Commands:
audioStatus
audioVolume
closeApp appid
getTVChannel
input3DOff
input3DOn
inputChannelDown
inputChannelUp
inputMediaFastForward
inputMediaPause
inputMediaPlay
inputMediaRewind
inputMediaStop
listApps
listChannels
listInputs
listServices
mute muted
notification message
off
on
openAppWithPayload payload
openBrowserAt url
openYoutubeId videoid
openYoutubeURL url
setInput input_id
setTVChannel channel
setVolume level
startApp appid
swInfo
volumeDown
volumeUp
Assuming you have a websocket port 3000 open on your TV, you can list apps using LGWebOSRemote:
$ lgtv listApps | jq '.payload.launchPoints[] | .id + ": " + .title'
"com.webos.app.hdmi3: HDMI 3 - PC"
"youtube.leanback.v4: YouTube"
... or simply run lgtv listApps for unfiltered JSON.
Tested on an LG UK6750PLD with webOS 4.1.0.
In the libraries i've seen, button codes were hard-coded as commands.

Smart Sheet API 2.1.1, Download attachment but url is missing

Download attachement to Local drive ##
for(Row r : rows){
PagedResult<Attachment> attachments = smartsheet.sheetResources().rowResources().attachmentResources().getAttachments(sheetId, r.getId(), null);
System.out.println("attachments"+attachments.getData().size());
if(attachments.getData().size() > 0){
for(Attachment at : attachments.getData()){
System.out.println(String.format("Attachement ID[%s], URL{%s}",at.getId(),at.getUrl()));
}
Output::
Attachement ID[2625191160375172], URL{null}
Attachement
ID[3215061968807812], URL{null}
Attachement ID[6310196327802756],
URL{null}
Attachement ID[5565993922652036], URL{null}
I understand now, iterating the object and reaching out the attachement will not give you the url, infact you have to get id from that object and then query smart sheet again with GetAttachment procedure i. e
Attachment at = smartsheet.sheetResources().attachmentResources().getAttachment(sheetId, att.getId());

How to obtain the image path/ url from a file uploaded on an openshift data dir to be stored in a postgresql database?

I am a self-taught programming newbie here so please bear with me. I am trying to create a site which allows users to upload their images on. With the patience of another user, I was able to get some answers as to how to create and allow users to upload their images onto the data drive on openshift. However, now I need to be able to store the image path or url onto a postgresql database (which can be called on later) so that each user will be able to keep track of the images that they have uploaded. I am currently stymied by this.
Here are the fragments of code which I feel plays a big role in answering this question:
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column('todo_id', db.Integer, primary_key=True)
title = db.Column(db.String(60))
text = db.Column(db.String)
done = db.Column(db.Boolean)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
image_url = db.Column(db.String)
def __init__(self, title, text, image_url):
self.title = title
self.text = text
self.image_url = image_url
self.done = False
self.pub_date = datetime.utcnow()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
#app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
return redirect(url_for('uploaded_file',
filename=filename))
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
#app.route('/new', methods=['GET', 'POST'])
#login_required
def new():
if request.method == 'POST':
if not request.form['title']:
flash('Title is required', 'error')
elif not request.form['text']:
flash('Text is required', 'error')
else:
todo = Todo(request.form['title'], request.form['text'])
todo.user = g.user
db.session.add(todo)
db.session.commit()
flash('Todo item was successfully created')
return redirect(url_for('index'))
return render_template('new.html')
The current code that I have is pieced together by various tutorials and examples.
Currently, I am trying to merge the "Todo" db, "upload" function and "new" function and am having very little success. Using the little knowledge I have, I have merely added the "image_url" portions in which will be a column that is intended to house the image path. I would greatly appreciate it if somebody could shed some light on this conundrum. Thanks a million.
Respectfully,
Max

How to mail a screen captured image using corona SDK

I am new to corona SDK, but I've managed to capture my app scene using the following code:
local function captureArea()
local myCaptureImage = display.captureBounds(display.currentStage.contentBounds, true)
myCaptureImage:removeSelf()
myCaptureImage = nil
end
bg:addEventListener("tap",captureArea)
This works perfectly.
Now I need to send the captured image(with a specific name, say: screen_1.png) to my friend via email. I've used Composing E-mail and SMS for refference, but I fail to understand how I can add this saved image in the attachment field of mail options.
Please give me a proper solution that how can I attach and send the above saved image via email.
display.captureBounds is good for saving the whole screen to the directory. But it usually saves the file with increase in last index. So it may be difficult to read them correctly. So I prefer display.save. But it is not a straight way.
For doing this, you have to:
First create a localgroup.
Then add the screen objects to that group.
Return the display group
Use display.save to save the entire group displayed.
Create mail option and add attachment image from baseDirectory
Call mail Popup
I am giving a sample here:
-- creating the display group --
local localGroup = display.newGroup()
-- creating display objects and adding it to the group --
local bg = display.newRect(0,0,_w,_h)
bg.x = 160
bg.y = 240
bg:setFillColor(150)
localGroup:insert(bg)
local rect = display.newRect(0,0,50,50)
rect.x = 30+math.random(260)
rect.y = 30+math.random(420)
localGroup:insert(rect)
-- Then do as follows --
local function takePhoto_andSendMail()
-- take screen shot to baseDirectory --
local baseDir = system.DocumentsDirectory
display.save( localGroup, "myScreenshot.jpg", baseDir )
-- Create mail options --
local options =
{
to = { "krishnarajsalim#gmail.com",},
subject = "My Level",
body = "Add this...",
attachment =
{
{ baseDir=system.DocumentsDirectory, filename="myScreenshot.jpg", type="image" },
},
}
-- Send mail --
native.showPopup("mail", options)
end
rect:addEventListener("tap",takePhoto_andSendMail)
This will do it...
Keep coding........ :)