The snowy weather here on Vancouver Island has given me some unexpected 
time to work on this.  I now have a working template file and python script 
that will produce and post weewx data to a Mastodon account.
Just setup an account on your favourite Mastodon server, 
mark it as a bot, 
create an API/Client Key (under development in your account's preferences)
install the template file to one of your skins (I just added it to the 
Standard skin.
put the python file somewhere it can be run with cron
run the python file with a command like this:

sudo python3  weewx_to_mastodon.py --server https://mstdn.ca --wxdata 
https://mywebpage.com/mastodon.json --api_key biglongstring234fssdf

I've attached my working files if anyone is itching to have it, excuse the 
messy code but it should be fairly self explanatory. You should only really 
need to modify the values in the json.tmpl file.

On Sunday, December 18, 2022 at 3:40:31 PM UTC-8 Chris Alemany wrote:

> Here is the promised link to the fellow who created a Python script from 
> cumulus on Mac to Mastodon/ActivityPub: 
> https://github.com/buffaloseven/CumulusMX-Customizations/tree/main/integrations
>
> Sent from my iPhone
>
> On Dec 15, 2022, at 6:24 AM, Chris Alemany <chri...@gmail.com> wrote:
>
> Hi all,
>
>
>
> Has anyone had a go at having weewx post to Mastodon/Fediverse, either to 
> an existing @user@server or as an independent instance?
>
> There is at least one fellow who has written some Python to do it from his 
> cumulus based system. I will share his GitHub project if someone thinks 
> they can do it.
>
> Cheers
> Chris
>
> Sent from my iPhone
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"weewx-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to weewx-user+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/weewx-user/aa08bcaa-6e19-4e39-b0bc-16093034a910n%40googlegroups.com.
#!/usr/bin/env python3

import requests
import argparse
import math
import json

class Mastodon_MX:
	def __init__(self):
		arg_parser = argparse.ArgumentParser(prog = 'Mastodon Auto-Toot', description = 'Programatically send WeeWX weather conditions to Mastodon.')
		arg_parser.add_argument('--server', help='Domain of your Mastodon instance. For example, https://mstdn.ca')
		arg_parser.add_argument('--api_key', help='API key (Access Token) given from the Mastodon developer section.')
		arg_parser.add_argument('--wxdata', default="http://localhost:8998";, help='Location of Weather data file')
		self.args = arg_parser.parse_args()
		# Mastodon Information
		self.mastodon_url = self.args.server + "/api/v1/statuses"
		self.mastodon_auth = {'Authorization': 'Bearer ' + self.args.api_key}
		
		self.post_contents = ""

	def generate_conditions(self):
		
		# Get the current conditions from the API
		local_api = self.args.wxdata
		self.conditions = requests.get(local_api)
		if (self.conditions.status_code == 200):
			self.conditions = self.conditions.json()
			fullText_toot = f'''{self.conditions[0]['fullText']} \n DriveBC Webcams: {self.conditions[0]['cam1']}'''
			
			
			""" THIS IS THE PREVIOUS CODE WHICH I WOULD LIKE TO USE BUT FOR NOW, JUST TEXT
		
			conditions = conditions.json()
			# Create base temperature string.
			temp_toot = f'''Temperature {conditions["temp"]} °C with a dew point of {conditions["dew"]} °C ({conditions["hum"]}% RH).'''
			
			# Append a wind chill if eligible.
			wind_chill = 13.12 + (0.6215 * float(conditions["temp"])) - (11.37 * pow(float(conditions["wspeed"]),0.16)) + (0.3965 * float(conditions["temp"]) * pow(float(conditions["wspeed"]),0.16))
			wind_chill = round(wind_chill)
			if (wind_chill > 0):
				wind_chill = round(float(conditions["temp"]))
			
			wind_chill_temp_difference = float(conditions["temp"]) - wind_chill
			if (wind_chill < -40):
				temp_toot = temp_toot + f''' Extreme wind chill of {wind_chill}.'''
			elif (wind_chill < -20 and wind_chill_temp_difference > 4):
				temp_toot = temp_toot + f''' Wind chill of {wind_chill}.'''
			elif (wind_chill < -10 and wind_chill_temp_difference > 6):
				temp_toot = temp_toot + f''' Wind chill of {wind_chill}.'''
			
			# Append a humidex if eligible.
			humidex = float(conditions["temp"]) + (0.555 * (6.11 * pow(math.e, 5417.7530*((1/273.16) - (1/(273.15+float(conditions["dew"])))))-10))
			humidex = round(humidex*10) / 10
			humidex_temp_difference = humidex - float(conditions["temp"])
			if (humidex > 40):
				temp_toot = temp_toot + f''' Extreme humidex of {humidex}'''
			elif (humidex > 30 and humidex_temp_difference > 3):
				temp_toot = temp_toot + f''' Humidex humidex of {humidex}'''
			elif (humidex > 20 and humidex_temp_difference > 5):
				temp_toot = temp_toot + f''' Humidex humidex of {humidex}'''
			
			# Pressure component.
			press_toot = f'''Barometer {conditions["press"]} mb, {conditions["presstrend"].lower()}.'''
			
			# Wind component
			if (conditions["wspeed"] == "0"):
				wind_toot = "Winds are calm."
			else:
				wind_toot = f'''Wind {conditions["wdir"]} {conditions["wspeed"]} gusting {conditions["wgust"]} km/h ({conditions["avgbearing"]}°).'''
				
			# Precipitation component
			precip_toot = ""
			if (float(conditions["rrate"]) > 50 and float(conditions["temp"]) > 2):
				precip_toot = precip_toot + f'''Intense rain with a rate of {conditions["rrate"]} mm/hr. '''
			elif (float(conditions["rrate"]) > 7.6 and float(conditions["temp"]) > 2):
				precip_toot = precip_toot + f'''Heavy rain with a rate of {conditions["rrate"]} mm/hr. '''
			elif (float(conditions["rrate"]) > 2.4 and float(conditions["temp"]) > 2):
				precip_toot = precip_toot + f'''Moderate rain with a rate of {conditions["rrate"]} mm/hr. '''
			elif (float(conditions["rrate"]) > 0 and float(conditions["temp"]) > 2):
				precip_toot = precip_toot + f'''Light rain with a rate of {conditions["rrate"]} mm/hr. '''
			
			if (float(conditions["rhour"]) > 0):
				precip_toot = precip_toot + f'''1-hour precipitation of {conditions["rhour"]} mm, {conditions["r24hour"]} mm last 24 hours.'''
			elif (float(conditions['r24hour']) > 0):
				precip_toot = precip_toot + f'''24-hour precipitation {conditions["r24hour"]} mm.'''
			elif (float(conditions["temp"]) < -5):
				precip_toot = precip_toot + f'''No liquid precipitation or melt in the last 24 hours.'''
			else: 
				precip_toot = precip_toot + f'''No precipitation in the last 24 hours.'''
			
			self.post_contents = f'''{temp_toot} {press_toot} {wind_toot} {precip_toot}'''
				
			"""
			
			
			self.post_contents = f'''{fullText_toot}'''
			
			print(self.post_contents)
			#print(self.conditions.url)

	def submit_post(self):
		post = {'status': f'''{self.post_contents}'''}
		# Send the toot and return its URL.
		r = requests.post(self.mastodon_url, data=post, headers=self.mastodon_auth)
		print(r.json()['uri'])
	
	def send_conditions(self):
		self.generate_conditions()
		self.submit_post()
		
	def send_dailySummary():
		self.generate_summarry()
		self.submit_post()
		
if '__main__':
	mcmx = Mastodon_MX()
	mcmx.send_conditions()

Attachment: mastodon.json.tmpl
Description: Binary data

Reply via email to