หน้าเว็บ

แสดงบทความที่มีป้ายกำกับ Python แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Python แสดงบทความทั้งหมด

วันพุธที่ 27 พฤศจิกายน พ.ศ. 2562

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Run ที่เครื่องที่ออกเน็ต ได้ ในที่นี้ใช้เครื่อง Extranet
1. ติดตั้งโปรแกรม
  1. sudo apt-get install python-pip

2. ติดตั้ง Slack Client
  1. pip install slackclient
3. สร้าง code removeSlack.py
  1. from slackclient import SlackClient
  2. #from time import sleep
  3. import time
  4. #import datetime
  5. from datetime import datetime, timedelta
  6.  
  7. legacy_token = 'xxxxxx'  # don't if you share your code
  8. channel = 'Cxxxxx'  # the id of the channel to delete all msgs inside
  9.  
  10. sc = SlackClient(legacy_token)
  11. response = sc.api_call('channels.info', channel=channel)
  12.  
  13. #oldest_ts = response['channel']['created']
  14. date_days_ago = datetime.now() - timedelta(days=60)
  15. oldest_ts = time.mktime(date_days_ago.timetuple())
  16. print(datetime.fromtimestamp(oldest_ts))
  17.  
  18. date_days_ago = datetime.now() - timedelta(days=30)
  19. latest_ts = time.mktime(date_days_ago.timetuple())
  20. print(datetime.fromtimestamp(latest_ts))
  21.  
  22. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  23. allmsgs = [item['ts'] for item in response['messages']]
  24. print(len(allmsgs))
  25. for msg in allmsgs:
  26.     sc.api_call('chat.delete', channel=channel, ts=msg)
  27.     time.sleep(1)
  28. ########### Chanel Server  ###################
  29. channel = 'Cxxxxx'
  30.  
  31. sc = SlackClient(legacy_token)
  32. response = sc.api_call('channels.info', channel=channel)
  33.  
  34. #oldest_ts = response['channel']['created']
  35. date_days_ago = datetime.now() - timedelta(days=60)
  36. oldest_ts = time.mktime(date_days_ago.timetuple())
  37. print(datetime.fromtimestamp(oldest_ts))
  38.  
  39. date_days_ago = datetime.now() - timedelta(days=30)
  40. latest_ts = time.mktime(date_days_ago.timetuple())
  41. print(datetime.fromtimestamp(latest_ts))
  42.  
  43. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  44. allmsgs = [item['ts'] for item in response['messages']]
  45. print(len(allmsgs))
  46. for msg in allmsgs:
  47.     sc.api_call('chat.delete', channel=channel, ts=msg)
  48.     time.sleep(1)
4. chmod ให้ Run ได้
5. สร้าง Cront ให้ run ตามที่ต้องการในที่นี้ run อาทิตย์ละครั้ง วันจันทร์
0 0 * * 1 python /home/pi/removeSlak.py >> /home/pi/removeSlack.log 2>&1

วันอังคารที่ 28 พฤษภาคม พ.ศ. 2562

Code Python ส่ง Slack ใหม่

Code Python ส่ง Slack ใหม่
Code เดิมส่งรูปสุดท้าย บางครั้งได้รูปว่าง
แก้ Code ใหม่เอารูปที่ 4 นับจากที่ Video มีการบันทึก
แล้วลบ jpg ทิ้ง
  1.  
  2. from slackclient import SlackClient
  3.  
  4. sc = SlackClient("xoxb-XXXXXXX")
  5.  
  6. import glob
  7. import os
  8.  
  9. #list jpg to array
  10. list_of_files = glob.glob('/home/pi/Pictures/*.jpg')
  11. if len(list_of_files) > 4:
  12.   file_select = list_of_files[4]
  13.   with open(file_select) as file_content:
  14.        sc.api_call(
  15.          "files.upload",
  16.          channels="CF6GEHBDF",
  17.          file=file_content,
  18.          title="IP Camera Room A 192.168.2.133."
  19.        )
  20. #delete jpg
  21. for i in glob.glob("/home/pi/Pictures/*.jpg"):
  22.   os.remove(i)

วันอังคารที่ 27 มีนาคม พ.ศ. 2561

Python : Python ส่งค่าเข้า MQTT

Python : Python ส่งค่าเข้า MQTT
  1.        # Start MQTT #
  2.         import paho.mqtt.client as mqtt
  3.  
  4.         mqttc = mqtt.Client("python_pub")
  5.         mqttc.connect("192.168.2.200", 1883)
  6.         mqttc.publish("hass/temperature_server_A", temperature)
  7.         mqttc.loop(2) #timeout = 2s
  8.  
  9.         # End MQTT #


Error ImportError: No module named paho.mqtt.client
  1. root@raspberrypi:/home/pi# python mqtt.py
  2. Traceback (most recent call last):
  3.   File "mqtt.py", line 21, in <module>
  4.     import paho.mqtt.client as mqtt
  5. ImportError: No module named paho.mqtt.client


  1. sudo apt-get install python-pip
  1. pip install paho-mqtt



คำสั่งพื้นฐาน

ดูสถานะ error สามารถใช้ start stop restart status
ไว้ Restart ถ้า Restart ผ่านหน้า Web แล้วไม่ทำงาน
  1. sudo systemctl status home-assistant@homeassistant


Python Auto Start Background On Pi

  1. chmod 755 /etc/rc.local

add before "exit 0"
  1. (sleep 10;sudo python /home/pi/mqttAir.py) &

วันอาทิตย์ที่ 6 พฤศจิกายน พ.ศ. 2559

Python : python call file python , While, Time Delay

python : python call file python

Code : Call other file
  1. import os
  2. os.system('filename.py')

Example :
  1. os.system('/home/pi/checkair.py')


Code : Time Delay
  1. import time
  2. while True:
  3.     print "This prints once a minute."
  4.     time.sleep(60)  # Delay for 1 minute (60 seconds)


Example : All
  1. #!/usr/bin/python
  2. #### Check temperature Adafruit_DHT 22 23 #######
  3. import sys
  4. import os
  5. import Adafruit_DHT
  6. import time
  7.  
  8. humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  9.  
  10. #while(humidity is None and temperature is None):
  11. while(temperature is None):
  12.         humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  13.         time.sleep(10)  # Delay for 10 seconds before loop.
  14.  
  15. #### On Or Off Relay By Piface  #####
  16. import pifacedigitalio
  17. pf = pifacedigitalio.PiFaceDigital()
  18. import smtplib
  19.  
  20. print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
  21. if temperature > 27:
  22.         pf.relays[1].turn_on()
  23.         pf.relays[0].turn_on()
  24.  
  25.         from smtplib import SMTP
  26.  
  27.         recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  28.         def send_email (message, status):
  29.                 fromaddr = 'scivalve.suwit@gmail.com'
  30.                 server = SMTP('smtp.gmail.com:587')
  31.                 server.ehlo()
  32.                 server.starttls()
  33.                 server.ehlo()
  34.                 server.login('scivalve.suwit@gmail.com', 'PASSWORD')
  35.                 server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  36.                 server.quit()
  37.  
  38.         send_email("High temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "High temp alert! Turn ON relays.")
  39. else:
  40.         pf.relays[0].turn_off()
  41.         pf.relays[1].turn_off()
  42.  
  43. pf.deinit_board()
  44.  

http://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another

วันศุกร์ที่ 9 กันยายน พ.ศ. 2559

Python :: python send email gmail One User recipient.

Python :: python send email gmail One User recipient.
1. Code
  1. import smtplib
  2.  
  3. fromaddr = 'fromuser@gmail.com'
  4. toaddrs  = 'touser@gmail.com'
  5. msg = 'There was a terrible error that occured and I wanted you to know!'
  6.  
  7.  
  8. # Credentials (if needed)
  9. username = 'username'
  10. password = 'password'
  11.  
  12. # The actual mail send
  13. server = smtplib.SMTP('smtp.gmail.com:587')
  14. server.starttls()
  15. server.login(username,password)
  16. server.sendmail(fromaddr, toaddrs, msg)
  17. server.quit()

Example :: https://www.nixtutor.com/linux/send-mai ... th-python/

Raspberry PI :: Raspberry PI Fix IP

Raspberry PI :: Raspberry PI Fix IP
1. Run Command
  1. nano /etc/network/interfaces

2. Example Fix IP
  1. auto eth0
  2. allow-hotplug eth0
  3. #iface eth0 inet manual
  4. iface eth0 inet static
  5. #your static IP
  6. address 192.168.0.3
  7. #your gateway IP
  8. gateway 192.168.0.2
  9. netmask 255.255.255.0
  10. #your network address "family"
  11. network 192.168.0.2
  12. broadcast 192.168.0.255

3. Restart Service
  1. /etc/init.d/networking restart

http://elinux.org/RPi_Setting_up_a_static_IP_in_Debian

Python :: python send email gmail multiple recipients.

Python :: python send email gmail multiple recipients.
1. Create file sendmail.py
2. Insert Code
  1. #!/usr/bin/python
  2. import smtplib
  3. from smtplib import SMTP
  4.  
  5. recipients = ['suwit.jph@gmail.com', 'suwit_jph@hotmail.co.th']
  6.  
  7. def send_email (message, status):
  8.     fromaddr = 'scivalve.suwit@gmail.com'
  9.     server = SMTP('smtp.gmail.com:587')
  10.     server.ehlo()
  11.     server.starttls()
  12.     server.ehlo()
  13.     server.login('scivalve.suwit@gmail.com', 'password')
  14.     server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  15.     server.quit()
  16.  
  17. send_email("Test","Test send mail")
  18.  
  19.  

3. Test Run Command.
  1. ./sendmail.py

Example : http://stackoverflow.com/questions/2050 ... -addresses

Python :: Python + Piface เช็คอุหภูมิปิดเปิดแอร์ Auto

Python :: Python + Piface เช็คอุณหภูมิปิดเปิดแอร์ Auto
1. ติดตั้ง OS
2. ติดตั้ง Python
  1. sudo apt-get install python{,3}-pifacedigitalio

3. ติดตั้ง library สำหรับ Run python เช็คอุณหภูมิ https://learn.adafruit.com/dht-humidity ... ll-updated
  1. cd Adafruit_Python_DHT
  1. sudo apt-get update
  1. sudo apt-get install build-essential python-dev python-openssl
  1. sudo python setup.py instal
l
4. สร้างไฟล์ checkair.py ด้วยคำสั่ง
  1. nano checkair.py

ใส่ code
  1.                                                                                               
  2. #!/usr/bin/python
  3. #### Check temperature Adafruit_DHT 22 23 #######
  4. import sys
  5.  
  6. import Adafruit_DHT
  7.  
  8. # Parse command line parameters.
  9. # Use This.
  10. #sensor_args = { '11': Adafruit_DHT.DHT11,
  11. #                                '22': Adafruit_DHT.DHT22,
  12. #                                '2302': Adafruit_DHT.AM2302 }
  13. #if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
  14. #        sensor = sensor_args[sys.argv[1]]
  15. #        pin = sys.argv[2]
  16. #else:
  17. #        print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#'
  18. #        print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4'
  19. #        sys.exit(1)
  20.  
  21. # Try to grab a sensor reading.  Use the read_retry method which will retry up
  22. # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
  23. #humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
  24. humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  25.  
  26.  
  27. # Un-comment the line below to convert the temperature to Fahrenheit.
  28. # temperature = temperature * 9/5.0 + 32
  29.  
  30. # Note that sometimes you won't get a reading and
  31. # the results will be null (because Linux can't
  32. # guarantee the timing of calls to read the sensor).  
  33. # If this happens try again!
  34. if humidity is not None and temperature is not None:
  35.         print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
  36. else:
  37.         print 'Failed to get reading. Try again!'
  38.         sys.exit(1)
  39.  
  40. #### Opne and Close Relay By Piface  #####
  41.  
  42. import pifacedigitalio
  43. pf = pifacedigitalio.PiFaceDigital()
  44.  
  45. #pf.leds[1].turn_on()
  46. #pf.leds[2].turn_on()
  47. #pf.leds[3].turn_on()
  48. #pf.leds[4].turn_on()
  49. #pf.leds[5].turn_on()
  50. #pf.leds[6].turn_on()
  51. #pf.leds[7].turn_on()
  52. #### ON #####
  53. import smtplib
  54.  
  55. if temperature > 27:
  56.         pf.relays[1].turn_on()
  57.         pf.relays[0].turn_on()
  58.  
  59.         from smtplib import SMTP
  60.  
  61.         recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  62.  
  63.         def send_email (message, status):
  64.                 fromaddr = 'mail'
  65.                 server = SMTP('smtp.gmail.com:587')
  66.                 server.ehlo()
  67.                 server.starttls()
  68.                 server.ehlo()
  69.                 server.login('mail', 'password')
  70.                 server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  71.                 server.quit()
  72.  
  73.         send_email("High temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "High temp alert! Turn ON relays.")
  74. else:
  75.         pf.relays[0].turn_off()
  76.         pf.relays[1].turn_off()
  77.  
  78.         #from smtplib import SMTP
  79.  
  80.         #recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  81.  
  82.         #def send_email (message, status):
  83.         #        fromaddr = 'mail'
  84.         #        server = SMTP('smtp.gmail.com:587')
  85.         #        server.ehlo()
  86.         #        server.starttls()
  87.         #        server.ehlo()
  88.         #        server.login('mail', 'password')
  89.         #        server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  90.         #        server.quit()
  91.         #send_email("Temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "Temp alert! Turn OFF Relays.")
  92.  
  93. pf.deinit_board()
  94.  
  95.  

5. Run ไฟล์ py ด้วยคำสั่ง
  1. ./checkair.py 22 23

6. ตั้งให้ Run ตามเวลาใน crontab
  1. crontab -e

เพิ่มเวลาที่ต้องการให้ run เข้าไป
*/5 * * * * ./checkair.py 22 23

การต่อ วงจร ตามรูป

Python :: Python Check Speed Internet get Data for USE. PHP

Python :: Python Check Speed Internet get Data for USE.
1. Install follow This. http://porpramarn.blogspot.com/2016/09/python-python-check-speed-internet-on.html
2. Create File nettest.py
  1. nano nettest.py

3. Insert This Code.
  1. #!/usr/bin/python
  2. import os
  3. import sys
  4. import csv
  5. import datetime
  6. import time
  7. #import twitter
  8.  
  9. def test():
  10.  
  11.         #run speedtest-cli
  12.         print 'running test'
  13.         # /usr/bin/speedtest-cli
  14.         a = os.popen("python /usr/bin/speedtest-cli --simple").read()
  15.         # a = os.popen("python /home/pi/speedtest/speedtest-cli --simple").read()
  16.         print 'ran'
  17.         #split the 3 line result (ping,down,up)
  18.         lines = a.split('\n')
  19.         print a
  20.         ts = time.time()
  21.         date =datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
  22.         #if speedtest could not connect set the speeds to 0
  23.         if "Cannot" in a:
  24.                 p = 100
  25.                 d = 0
  26.                 u = 0
  27.         #extract the values for ping down and up values
  28.         else:
  29.                 p = lines[0][6:11]
  30.                 d = lines[1][10:14]
  31.                 u = lines[2][8:12]
  32.         print date,p, d, u
  33.         #save the data to file for local network plotting
  34.         # out_file = open('/var/www/assets/data.csv', 'a')
  35.         out_file = open('/home/pi/data.csv', 'a')
  36.  
  37.         writer = csv.writer(out_file)
  38.         writer.writerow((ts*1000,p,d,u))
  39.         out_file.close()
  40.         return
  41.  
  42. if __name__ == '__main__':
  43.         test()
  44.         print 'completed'
  45.  

4. Run python
  1. python nettest.py

Data
1454725814235.995,23.64,39.1,21.6

5. Use file data.csv Or Insert to database.

http://pastebin.com/WMEh802V

######################################################################
ติดตั้ง phpmyadmin เพิ่มต่อเพื่อดึงข้อมูลเข้า database เก็บไว้ใช้งานต่อไป
ติดตั้ง
  1. sudo apt-get install apache2
  1. sudo apt-get install mysql-server
  1. sudo apt-get install php5
  1. sudo apt-get install phpmyadmin


1. สร้าง ไฟล์ net-check.php ที่ var/www/
  1. nano /var/www/nano net-check.php

2. เพิ่มคนสำหรับ Check Speed Net ที่ Python และส่งเมล์เตือนเมื่อ Speed ได้ต่ำกว่ากำหนด Code
  1. <?php
  2. // Read Data From DHT22
  3. $strDateTime = date("Y-m-d H:i:s");
  4. //$strDhtData = exec("/usr/local/bin/Adafruit_DHT 22 23");
  5.  
  6. $command = escapeshellcmd('/home/pi/nettest.py');
  7. $output = shell_exec($command);
  8. //echo $output;
  9.  
  10. list($date, $time, $ping, $download, $upload) = explode(" ", $output);
  11.  
  12. echo $date.",".$time.",".$ping.",".$download.",".$upload;
  13.  
  14.         $fp = fopen('/var/www/data-net.txt', 'a+');
  15.         fwrite($fp, "Date = $, {$output}");
  16.         fclose($fp);
  17.  
  18.         if(floatval($download) < 50){
  19.                 $strToPost = "\nFrom Raspberry : Date = {$date} {$time} : Ping = {$ping} : Download = {$download} : Upload = {$upload} \n";
  20.                 //echo $strToPost;
  21. $ret = mail("komkid@gmail.com,suwit.jph@gmail.com,nontiwaza@gmail.com", "Internet Test Speed is low. Please Check Internet Connection.", $strToPost, "From: SCI Raspberry\n");
  22.                 //$ret = mail("suwit.jph@gmail.com","Internet Test Speed is low. Please Check Internet Connection.", $strToPost, "From: SCI Raspberry\n");
  23.                 if($ret)
  24.                         echo "OK {$output}";
  25.                 else
  26.                         echo "Failed!";
  27.         }
  28.  
  29. ?>
  30.  
  31.  


3. Chmod file pytho เพื่อให้ php สามารถ run ได้
  1. chmod +x nettest.py
ทดลอง Run ผ่าน Terminal แล้วดูผล
  1. /usr/bin/php /var/www/net-check.php

4. ตั้งเวลาให้ Run ทุก 1 ชั่วโมง โดยใช้คำสั่ง
  1. crontab -e

และเพิ่ม
  1. #Check Internet Every 1 Hours
  2. 0 * * * * /usr/bin/php /var/www/temp-alert.php

http://pastebin.com/WMEh802V

Python :: Python Check Speed Internet On Ubuntu Or PI

Python :: Python Check Speed Internet On Ubuntu Or PI

http://ubuntuserverguide.com/2014/01/ho ... erver.html

Installing speedtest-cli Using pip command:

1. install pip with the following command:
  1. sudo apt-get install python-pip


2. Once pip installed, now install speedtest-cli by using pip command:
  1. sudo pip install speedtest-cli


3. Installing speedtest-cli Manually. To installing speedtest-cli in manually method you need to download the latest speedtest-cli python script from github:


4. make speedtest_cli.py executable
  1. sudo chmod a+rx speedtest_cli.py


5. Move speedtest_cli.py to directory /usr/bin
  1. sudo mv speedtest_cli.py /usr/bin/speedtest-cli


Test Connection Speed using Speedtest-cli. It is easy to check internet speed with speedtest-cli. Just type command speedtest-cli without any arguments.
  1. speedtest-cli 
  1. speedtest-cli --share

For a list of servers Speedtest.net available worldwide, use “–list” option. An ordered list of servers is displayed Speedtest.net (geographically nearest first).
  1. speedtest-cli --list
OR
  1. speedtest-cli --list | grep Thailand
 
  1. speedtest-cli --server 4347


More information about speedtest-cli, type:
  1. speedtest-cli --help