Click to view the code
from import *
import requests
import json
# Configuration information
PRINTER_IP = '1.1.1.1' # Printer IP
COMMUNITY_STRING = 'public' # SNMP group name
DINGTALK_WEBHOOK = '/robot/send?test' # Replace with DingTalk Robot Webhook Address
# Ricoh printer OID information
TONER_OIDS = {
'Black': '1.3.6.1.2.1.43.11.1.1.9.1.1',
'Cyan': '1.3.6.1.2.1.43.11.1.1.9.1.2',
'Magenta': '1.3.6.1.2.1.43.11.1.1.9.1.3',
'Yellow': '1.3.6.1.2.1.43.11.1.1.9.1.4',
'black_max': '1.3.6.1.2.1.43.11.1.1.8.1.1',
}
def get_snmp_value(oid):
"""Get SNMP value and handle exceptions"""
try:
error_indication, error_status, error_index, var_binds = next(
getCmd(SnmpEngine(),
CommunityData(COMMUNITY_STRING),
UdpTransportTarget((PRINTER_IP, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid)))
)
if error_indication:
print(f"SNMP error: {error_indication}")
return None
elif error_status:
print(f"SNMP error: {error_status.prettyPrint()}")
return None
return var_binds[0][1] if var_binds else None
except Exception as e:
print(f"SNMP query exception: {str(e)}")
return None
def send_dingtalk_message(message):
"""Send a message to DingTalk Robot""""
headers = {'Content-Type': 'application/json'}
payload = {
"msgtype": "markdown",
"markdown": {
"title": "Printer toner status",
"text": message
}
}
try:
response = (DINGTALK_WEBHOOK,
data=(payload),
headers=headers,
timeout=5)
response.raise_for_status()
print("Status has been sent to DingTalk")
except as e:
print(f"DingTalk message sending failed: {str(e)}")
def get_toner_status():
"""Get and format the toner status""""
print("Getting printer status...")
# Build message content
status_report = [
"### Ricoh IMC2000 Toner Status Report",
f"**IP address**: {PRINTER_IP} \n", # newline character is used in DingTalk markdown format
"|Color|Remaining|\n|-|-|"
]
for color, oid in TONER_OIDS.items():
if 'max' in color:
continue # Skip the maximum capacity value
value = get_snmp_value(oid)
if value is not None:
status_report.append(f"|{()}|{value}%|")
else:
status_report.append(f"|{()}|Fetch failed|")
# Send DingTalk Notification
send_dingtalk_message("\n".join(status_report))
if __name__ == "__main__":
get_toner_status()